From 969731d9cd0759e4990f4838e251afe325d23261 Mon Sep 17 00:00:00 2001 From: Naveen Hegde Date: Sat, 30 Dec 2017 02:02:44 +0530 Subject: [PATCH] Added Numeric String Sort Sorts an array of Numeric strings. An array of strings like 1,2,3,10,20,30,100,200,300 are sorted as 1,10,100,2,20,200,3,30,300 Conventionally. This programme sorts them in the correct numeric order i.e 1,2,3,10,20,30,100,200,300 --- NumericStringSort.cpp | 64 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 NumericStringSort.cpp diff --git a/NumericStringSort.cpp b/NumericStringSort.cpp new file mode 100644 index 000000000..726377ebe --- /dev/null +++ b/NumericStringSort.cpp @@ -0,0 +1,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 +#include +#include +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> n; + +vector v(n); +cout << "Enter the string of Numbers\n"; +for(int i=0;i> v[i]; +} + +sort(v.begin(),v.end()); +cout << "Elements sorted normally \n"; +for(int i=0;i