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
Similar Reads
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
12 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read