forked from TheAlgorithms/C-Plus-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumericStringSort.cpp
64 lines (52 loc) · 1.19 KB
/
NumericStringSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//Using general algorithms to sort a collection of strings results in alphanumeric sort.
//If it is a numeric string, it leads to unnatural sorting
//eg, an array of strings 1,10,100,2,20,200,3,30,300
//would be sorted in that same order by using conventional sorting,
//even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300
//This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool NumericSort(string a,string b)
{
while(a[0]=='0')
{
a.erase(a.begin());
}
while(b[0]=='0')
{
b.erase(b.begin());
}
int n=a.length();
int m=b.length();
if(n==m)
return a<b;
return n<m;
}
int main()
{
int n;
cout << "Enter number of elements to be sorted Numerically\n";
cin >> n;
vector<string> v(n);
cout << "Enter the string of Numbers\n";
for(int i=0;i<n;i++)
{
cin >> v[i];
}
sort(v.begin(),v.end());
cout << "Elements sorted normally \n";
for(int i=0;i<n;i++)
{
cout << v[i] << " ";
}
cout << "\n";
sort(v.begin(),v.end(),NumericSort);
cout << "Elements sorted Numerically \n";
for(int i=0;i<n;i++)
{
cout << v[i] << " ";
}
return 0;
}