Open In App

Sorting Big Integers

Last Updated : 18 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given an array of n positive integers, where each integer can have up to 106 digits, print the array elements in ascending order. 
Assumption: There are no leading zeros.

Examples

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

[Approach 1] - String Based

Since the integer size is extremely large and can't fit in long long (C/C++), we store numbers as strings and sort them using a custom comparator:

  • If the lengths differ, the shorter string comes first.
  • If lengths are the same, sort lexicographically (dictionary order).
C++
#include<bits/stdc++.h>
using namespace std;

// comp function to perform sorting
bool comp(const string &left, const string &right)
{
    if (left.size() == right.size())
        return left < right;

    else
        return left.size() < right.size();
}


vector<string> SortingBigIntegers(vector<string> &arr)
{
    vector<string> sortArr(arr.begin(), arr.end());

    // Inbuilt sort function using function as comp
    sort(sortArr.begin(), sortArr.end(), comp);

    return sortArr;
}

// Driver code of above implementation
int main()
{
    vector<string> arr = {"54", "724523015759812365462",
                    "870112101220845", "8723"};
    
    vector<string> sortArr = SortingBigIntegers(arr);
    
    for (auto &ele : sortArr)
        cout << ele << " ";
        
    return 0;
}
Java
import java.util.Arrays;
import java.util.Comparator;

public class GfG {

    // comp function to perform sorting
    static class comp implements Comparator<String> {
        public int compare(String left, String right)
        {
            // case1
            if (left.length() == right.length()) {
                return left.compareTo(right);
            }
            // case2
            else {
                return left.length() - right.length();
            }
        }
    }

    static String[] SortingBigIntegers(String[] arr)
    {
        int n = arr.length;
        String[] sortArr = Arrays.copyOf(arr, n);
        Arrays.sort(sortArr, new comp());

        return sortArr;
    }

    // Driver code of above implementation
    public static void main(String[] args)
    {
        String[] arr = { "54", "724523015759812365462",
                         "870112101220845", "8723" };

        String[] sortArr = SortingBigIntegers(arr);
        // Print the final sorted array
        for (String ele : sortArr) {
            System.out.print(ele + " ");
        }
    }
}
Python
def SortingBigIntegers(arr):
    
    n = len(arr)
    sortArr = arr
    arr.sort(key=lambda x: (len(x), x))

    return arr
# Driver code of above implementation
arr = ["54", "724523015759812365462",
       "870112101220845", "8723"]

sortArr = SortingBigIntegers(arr)

# Print the final sorted list using
# join method
print " ".join(sortArr)
C#
using System;
using System.Linq;
using System.Collections.Generic;

public class GfG {
    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;
            }
        }
    }

    static string[] SortingBigIntegers(string[] arr)
    {
        int n = arr.Length;

        // Copy the arr[] elements to sortArr[]
        string[] sortArr = (string[])arr.Clone();

        // Inbuilt sort function using function as comp
        Array.Sort(sortArr, new Comp());

        // Print the final sorted array
        return sortArr;
    }

    public static void Main()
    {
        string[] arr = { "54", "724523015759812365462",
                         "870112101220845", "8723" };
        int n = arr.Length;

        string[] sortArr = SortingBigIntegers(arr);
        foreach(string ele in sortArr)
        {
            Console.Write(ele + " ");
        }
    }
}
JavaScript
// comp function to perform sorting
function comp(left, right)
{

    // if length of both string are equals then sort
    // them in lexicographically order
    if (left.length == right.length)
        return left < right;

    // Otherwise sort them according to the length
    // of string in ascending order
    else
        return left.length - right.length;
}

// Function to sort arr[] elements according
// to integer value
function SortingBigIntegers(arr)
{

    // Copy the arr[] elements to sortArr[]
    let sortArr = [...arr ]

    // Inbuilt sort function using function as comp

    sortArr.sort(comp);
    return sortArr;
}

// Driver code of above implementation
let arr =["54", "724523015759812365462", "870112101220845",
        "8723"];

sortArr = SortingBigIntegers(arr);
console.log(sortArr.join(" "));
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)

[Approach 2] - Using Built-in Data Types

Python, Java, and JavaScript provide built-in data types like BigInteger (Java) and BigInt (JavaScript) to store extremely large integers, even up to 10^6 digits. These large numbers can be directly sorted using the inbuilt sorting functions available for arrays in these languages.

Java
import java.math.BigInteger;
import java.util.Arrays;

public class SortingBigIntegers {
    // Function to sort BigInteger array
    public static BigInteger[] sortBigIntegers(BigInteger[] arr) {
        Arrays.sort(arr);
        return arr;
    }

    public static void main(String[] args) {
        // Define an array of BigIntegers
        BigInteger[] arr = {
            new BigInteger("54"),
            new BigInteger("724523015759812365462"),
            new BigInteger("870112101220845"),
            new BigInteger("8723")
        };

        // Sort the array
        BigInteger[] sortedArr = sortBigIntegers(arr);

        // Print sorted array
        for (BigInteger num : sortedArr) {
            System.out.print(num + " ");
        }
    }
}
Python
def SortingBigIntegers(arr):
    # Sorting the array based on integer values
    arr.sort()
    return arr

# Driver code
arr = [54, 724523015759812365462, 870112101220845, 8723]

# Sorting the array
sortArr = SortingBigIntegers(arr)

# Printing the sorted list
print(" ".join(map(str, sortArr)))
JavaScript
function SortingBigIntegers(arr) {
    return arr.sort((a, b) => (a > b ? 1 : -1));
}

// Define an array of BigInts
let arr = [
    BigInt("54"),
    BigInt("724523015759812365462"),
    BigInt("870112101220845"),
    BigInt("8723")
];

// Sorting the array
let sortedArr = SortingBigIntegers(arr);

// Print sorted array (convert BigInts to strings)
console.log(sortedArr.map(String).join(" "));
Output: 54 8723 870112101220845 724523015759812365462

Time Complexity: O(n*log(n)*M), where n is number of elements in the array, M is number of digits in the largest integer.
Auxiliary space: O(1) (since sorting is done in-place)


Similar Post : 
Sort an array of large numbers



Article Tags :
Practice Tags :

Similar Reads