Sort an array of large numbers

3.3

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"};

The idea is to use sort() function in C++ or Arrays.sort in Java.

C++

// C++ program to sort large numbers represented
// as strings.
#include<bits/stdc++.h>
using namespace std;

// Returns true if str1 is smaller than str2.
bool compareNumbers(string str1, string str2)
{
    // Calculate lengths of both string
    int n1 = str1.length(), n2 = str2.length();

    if (n1 < n2)
       return true;
    if (n2 < n1)
       return false;

    // If lengths are same
    for (int i=0; i<n1; i++)
    {
       if (str1[i] < str2[i])
          return true;
       if (str1[i] > str2[i])
          return false;
    }

    return false;
}

// Function for sort an array of large numbers
// represented as strings
void sortLargeNumbers(string arr[], int n)
{
   sort(arr, arr+n, compareNumbers);
}

// Driver code
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

// Java program to sort large numbers represented
// as strings.
import java.io.*;
import java.util.*;

class main
{
    // Function for sort an array of large numbers
    // represented as strings
    static void sortLargeNumbers(String arr[])
    {
        // Refer below post for understanding below expression:
        // http://www.geeksforgeeks.org/lambda-expressions-java-8/ 
        Arrays.sort(arr, (left, right) ->
        {
            /* If length of left != right, then return 
               the diff of the length else  use compareTo
               function to compare values.*/
            if (left.length() != right.length())
                return left.length() - right.length();
             return left.compareTo(right);
        });
    }

    // Driver code
    public static void main(String args[])
    {
        String arr[] = {"5", "1237637463746732323",
                        "97987", "12" };
        sortLargeNumbers(arr);
        for (String s : arr)
            System.out.print(s + " ");
    }
}


Output:

5 12 97987 1237637463746732323 

Time complexity : O(k * n Log n) where k is length of the longest number. Here assumption is that the sort() function uses a O(n Log n) sorting algorithm.

Similar Post :
Sorting Big Integers

This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3.3 Average Difficulty : 3.3/5.0
Based on 13 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.