TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
numeric_string_sort.cpp
1// Using general algorithms to sort a collection of strings results in
2// alphanumeric sort. If it is a numeric string, it leads to unnatural sorting
3
4// eg, an array of strings 1,10,100,2,20,200,3,30,300
5// would be sorted in that same order by using conventional sorting,
6// even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300
7
8// This Programme uses a comparator to sort the array in Numerical order instead
9// of Alphanumeric order
10
11#include <algorithm>
12#include <iostream>
13#include <string>
14#include <vector>
15
16bool NumericSort(std::string a, std::string b) {
17 while (a[0] == '0') {
18 a.erase(a.begin());
19 }
20 while (b[0] == '0') {
21 b.erase(b.begin());
22 }
23 int n = a.length();
24 int m = b.length();
25 if (n == m)
26 return a < b;
27 return n < m;
28}
29
30int main() {
31 int n;
32 std::cout << "Enter number of elements to be sorted Numerically\n";
33 std::cin >> n;
34
35 std::vector<std::string> v(n);
36 std::cout << "Enter the string of Numbers\n";
37 for (int i = 0; i < n; i++) {
38 std::cin >> v[i];
39 }
40
41 sort(v.begin(), v.end());
42 std::cout << "Elements sorted normally \n";
43 for (int i = 0; i < n; i++) {
44 std::cout << v[i] << " ";
45 }
46 std::cout << "\n";
47
48 std::sort(v.begin(), v.end(), NumericSort);
49 std::cout << "Elements sorted Numerically \n";
50 for (int i = 0; i < n; i++) {
51 std::cout << v[i] << " ";
52 }
53
54 return 0;
55}
int main()
Main function.