Numeric String Sort Algorithm

The Numeric String Sort Algorithm, also known as the natural sort algorithm or alphanumeric sort, is a sorting algorithm designed to handle sequences of mixed numeric and non-numeric characters. It offers a more intuitive and human-friendly ordering of data compared to traditional sorting algorithms, like quicksort or mergesort, which only consider the ASCII values of characters. The key idea behind this algorithm is to group consecutive numeric characters together, treating them as a single numeric value, and order them accordingly alongside non-numeric characters. This ensures that strings with embedded numbers are sorted in a more natural way, as humans would typically expect. For example, when sorting a list of strings like ['file1', 'file10', 'file2', 'file20'], a traditional sorting algorithm would sort them based on the ASCII values of each character, resulting in the order ['file1', 'file10', 'file2', 'file20']. However, the Numeric String Sort Algorithm recognizes the numeric parts within each string and sorts them according to their actual numeric value, yielding a more natural sorting order: ['file1', 'file2', 'file10', 'file20']. This algorithm is particularly useful in situations where sorting filenames, version numbers, or other strings containing mixed numeric and non-numeric characters is required.
//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;
}

LANGUAGE:

DARK MODE: