Big Sorting[HackerRank Solution]
Problem:
Consider an array of numeric strings, , where each string is a positive number with anywhere from to 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, , denoting the number of strings in .
Each of the subsequent lines contains a string of integers describing an element of the array.
Constraints
- Each string is guaranteed to represent a positive integer without leading zeros.
- The total number of digits across all strings in is between and (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
Code:
#include <bits/stdc++.h>
using namespace std;
bool check(string str1, string str2)
{
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true;
if (n2 < n1)
return false;
for (int i=0; i<n1; i++)
{
if (str1[i] < str2[i])
return true;
if (str1[i] > str2[i])
return false;
}
return false;
}
int main(){
int n;
cin >> n;
vector<string> s;
for(int i=0;i<n;i++)
{
string s1;
cin>>s1;
s.push_back(s1);
}
sort(s.begin(),s.end(),check);
for(int i=0;i<s.size();i++)
{
cout<< s[i] <<endl;
}
return 0;
}
Passed all test cases!

Leave a reply to Beatris Kotow Cancel reply