Sort an array of large numbers
Last Updated :
29 Mar, 2022
Given an array of numbers where every number is represented as string. The numbers may be very large (may not fit in long long int), the task is to sort these numbers.
Examples:
Input : arr[] = {"5", "1237637463746732323", "12" };
Output : arr[] = {"5", "12", "1237637463746732323"};
Input : arr[] = {"50", "12", "12", "1"};
Output : arr[] = {"1", "12", "12", "50"};
Below is the implementation of the above idea.
C++
#include<bits/stdc++.h>
using namespace std;
bool compareNumbers(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 ;
}
void sortLargeNumbers(string arr[], int n)
{
sort(arr, arr+n, compareNumbers);
}
int main()
{
string arr[] = { "5" , "1237637463746732323" ,
"97987" , "12" };
int n = sizeof (arr)/ sizeof (arr[0]);
sortLargeNumbers(arr, n);
for ( int i=0; i<n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class main
{
static void sortLargeNumbers(String arr[])
{
Arrays.sort(arr, (left, right) ->
{
if (left.length() != right.length())
return left.length() - right.length();
return left.compareTo(right);
});
}
public static void main(String args[])
{
String arr[] = { "5" , "1237637463746732323" ,
"97987" , "12" };
sortLargeNumbers(arr);
for (String s : arr)
System.out.print(s + " " );
}
}
|
Python3
def sortLargeNumbers (arr, n):
arr.sort(key = int )
if __name__ = = '__main__' :
arr = [ "5" , "1237637463746732323" ,
"97987" , "12" ]
n = len (arr)
sortLargeNumbers(arr, n)
for i in arr:
print (i, end = ' ' )
|
C#
using System;
class GFG
{
static void sortLargeNumbers(String []arr)
{
for ( int i = 0; i < arr.Length - 1; i++)
{
String left = arr[i], right = arr[i + 1];
if (left.Length > right.Length)
{
arr[i] = right;
arr[i + 1] = left;
i -= 2;
}
}
}
public static void Main()
{
String []arr = { "5" , "1237637463746732323" ,
"97987" , "12" };
sortLargeNumbers(arr);
foreach (String s in arr)
Console.Write(s + " " );
}
}
|
Javascript
<script>
function sortLargeNumbers(arr)
{
for (let i = 0; i < arr.length - 1; i++)
{
let left = arr[i], right = arr[i + 1];
if (left.length > right.length)
{
arr[i] = right;
arr[i + 1] = left;
i -= 2;
}
}
}
let arr = [ "5" , "1237637463746732323" ,
"97987" , "12" ];
sortLargeNumbers(arr);
for (let s in arr)
document.write(arr[s] + " " );
</script>
|
Output:
5 12 97987 1237637463746732323
Time complexity: O(k * n Log n), Here assumption is that the sort() function uses a O(n Log n) sorting algorithm.
Auxiliary Space: O(1)
Similar Post:
Sorting Big Integers
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...