Big Sorting

Ashish Patel
Codebrace
Published in
2 min readFeb 27, 2017

Problem Link: Big Sorting

Consider an array of numeric strings, unsorted, where each string is a positive number with anywhere from 1 to 106 digits. Sort the array’s elements in non-decreasing (i.e., ascending) order of their real-world integer values and print each element of the sorted array on a new line.

Input Format

The first line contains an integer, n, denoting the number of strings in unsorted.
Each of the n subsequent lines contains a string of integers describing an element of the array.

Constraints

  • 1 ≤n ≤ 2.105
  • Each string is guaranteed to represent a positive integer without leading zeros.
  • The total number of digits across all strings in unsorted is between 1 and 106(inclusive).

Output Format

Print each element of the sorted array on a new line.

Sample Input 0

6
31415926535897932384626433832795
1
3
10
3
5

Sample Output 0

1
3
3
5
10
31415926535897932384626433832795

Explanation 0

The initial array of strings is unsorted = [31415926535897932384626433832795, 1, 3 , 10, 3, 5] When we order each string by the real-world integer value it represents, we get:
1 ≤3 ≤ 3 ≤ 5 ≤ 10 ≤ 31415926535897932384626433832795
We then print each value on a new line, from smallest to largest.

SOLUTION

This question is also of type easy. Simply take input in a vector of string and call sort function for it. Now catch here is that you have to give a parameter (third parameter ) with function sort which help you to decide the sort function for the comparisons. Now consider the following case:

  1. If length of first string is greater than length of second string it means first string is a greater number. Vice versa is true.
  2. Now if string is of equal length then we have have to compare the string character (or number) one by one and return whenever a mismatch occur. Now this case can be easily handle by string compare function.

CODE

#include <bits/stdc++.h>
using namespace std;
bool myfunction (string i,string j)
{
if(i.length()<j.length())
return true;
if(i.length()>j.length())
return false;
return (i.compare(j)<0);
}
int main(){
int n;
cin >> n;
vector<string> v(n);
for(int unsorted_i = 0; unsorted_i < n; unsorted_i++){
cin >> v[unsorted_i];
}
std::sort (v.begin(), v.end(), myfunction);
for(int unsorted_i = 0; unsorted_i < n; unsorted_i++)
cout<<v[unsorted_i]<<endl;
}

--

--

Ashish Patel
Codebrace

Big Data Engineer at Skyscanner , loves Competitive programming, Big Data.