Sorting Big Integers
Last Updated :
17 Dec, 2023
Given a array of n positive integers where each integer can have digits upto 106, print the array elements in ascending order.
Input: arr[] = {54, 724523015759812365462, 870112101220845, 8723}
Output: 54 8723 870112101220845 724523015759812365462
Explanation:
All elements of array are sorted in non-descending(i.e., ascending)
order of their integer value
Input: arr[] = {3643641264874311, 451234654453211101231,
4510122010112121012121}
Output: 3641264874311 451234654453211101231 4510122010112121012121
A naive approach is to use arbitrary precision data type such as int in python or Biginteger class in Java. But that approach will not be fruitful because internal conversion of string to int and then perform sorting will leads to slow down the calculations of addition and multiplications in binary number system.
C++
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector< long long > arr
= { 54, 724523015759812365462, 870112101220845,
8723 };
std::sort(arr.begin(), arr.end());
for ( long long i : arr) {
std::cout << i << std::endl;
}
return 0;
}
|
Java
import java.util.Arrays;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger[] arr = {
new BigInteger( "54" ),
new BigInteger( "724523015759812365462" ),
new BigInteger( "870112101220845" ),
new BigInteger( "8723" )
};
Arrays.sort(arr);
for (BigInteger i : arr) {
System.out.println(i);
}
}
}
|
Python3
arr = [ 54 , 724523015759812365462 , 870112101220845 , 8723 ]
arr.sort()
for i in arr:
print (i)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List< string > arrStrings = new List< string >
{
"54" , "724523015759812365462" , "870112101220845" , "8723"
};
arrStrings.Sort();
foreach ( string str in arrStrings)
{
Console.WriteLine(str);
}
}
}
|
Javascript
let arr = [54, 724523015759812365462, 870112101220845, 8723];
arr.sort();
for (let i = 0; i < arr.length; i++){
console.log(arr[i]);
}
|
Output
54
8723
870112101220845
724523015759812365462
Efficient Solution : As size of integer is very large even it can’t be fit in long long data type of C/C++, so we just need to input all numbers as strings and sort them using a comparison function. Following are the key points compare function:-
- If lengths of two strings are different, then we need to compare lengths to decide sorting order.
- If Lengths are same then we just need to compare both the strings in lexicographically order.
Assumption : There are no leading zeros.
C++
#include<bits/stdc++.h>
using namespace std;
bool comp( const string &left, const string &right)
{
if (left.size() == right.size())
return left < right;
else
return left.size() < right.size();
}
void SortingBigIntegers(string arr[], int n)
{
vector<string> sortArr(arr, arr + n);
sort(sortArr.begin(), sortArr.end(), comp);
for ( auto &ele : sortArr)
cout << ele << " " ;
}
int main()
{
string arr[] = { "54" , "724523015759812365462" ,
"870112101220845" , "8723" };
int n = sizeof (arr) / sizeof (arr[0]);
SortingBigIntegers(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Comparator;
public class Main
{
static class comp implements Comparator<String>
{
public int compare(String left, String right)
{
if (left.length() == right.length()) {
return left.compareTo(right);
}
else {
return left.length() - right.length();
}
}
}
static void SortingBigIntegers(String[] arr, int n)
{
String[] sortArr = Arrays.copyOf(arr, n);
Arrays.sort(sortArr, new comp());
for (String ele : sortArr) {
System.out.print(ele + " " );
}
}
public static void main(String[] args) {
String[] arr = { "54" , "724523015759812365462" ,
"870112101220845" , "8723" };
int n = arr.length;
SortingBigIntegers(arr, n);
}
}
|
Python
def SortingBigIntegers(arr, n):
arr.sort(key = lambda x: ( len (x), x))
arr = [ "54" , "724523015759812365462" ,
"870112101220845" , "8723" ]
n = len (arr)
SortingBigIntegers(arr, n)
print " " .join(arr)
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public class Comp : IComparer< string >
{
public int Compare( string left, string right)
{
if (left.Length == right.Length)
{
return String.Compare(left, right);
}
else
{
return left.Length - right.Length;
}
}
}
public static void SortingBigIntegers( string [] arr, int n)
{
string [] sortArr = ( string [])arr.Clone();
Array.Sort(sortArr, new Comp());
foreach ( string ele in sortArr)
{
Console.Write(ele + " " );
}
}
public static void Main()
{
string [] arr = { "54" , "724523015759812365462" ,
"870112101220845" , "8723" };
int n = arr.Length;
SortingBigIntegers(arr, n);
}
}
|
Javascript
<script>
function comp(left, right)
{
if (left.length == right.length)
return left < right;
else
return left.length - right.length;
}
function SortingBigIntegers(arr, n)
{
let sortArr = [...arr]
sortArr.sort(comp);
for (ele of sortArr)
document.write(ele + " " );
}
let arr = [ "54" , "724523015759812365462" ,
"870112101220845" , "8723" ]
let n = arr.length
SortingBigIntegers(arr, n);
</script>
|
Output: 54 8723 870112101220845 724523015759812365462
Time complexity: O(sum * log(n)) where sum is the total sum of all string length and n is size of array
Auxiliary space: O(n)
Similar Post :
Sort an array of large numbers
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...