Home

Big Sorting

Consider an array of numeric strings where each string is a positive number with anywhere from 1 to 10^6 digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array.


Example:

Input:

6
31415926535897932384626433832795
1
3
10
3
5

Output:

1 3 3 5 10 31415926535897932384626433832795

Approach:

Java


import java.util.Arrays;
import java.util.Comparator;

public class BigSorting {
    public static void main(String[] args) {
        String[] unsorted = { "31415926535897932384626433832795""1""3""10""3""5" };
        String[] result = bigSorting(unsorted);
        System.out.println(Arrays.toString(result));
    }

    private static String[] bigSorting(String[] unsorted) {
        Arrays.sort(unsorted, new Comparator<String>() {
            @Override
            public int compare(String o1String o2) {
                int x1 = o1.length();
                int x2 = o2.length();
                if (x1 == x2)
                    return o1.compareTo(o2);
                else
                    return x1 - x2;
            }
        });

        return unsorted;
    }

}


C++

#include <bits/stdc++.h>

using namespace std;

bool comp(string astring b)
{
    int n = a.size(), m = b.size();
    if (n != m)
        return n < m;
    return a < b;
}
vector<stringbigSorting(vector<stringunsorted)
{
    sort(unsorted.begin(), unsorted.end(), comp);
    return unsorted;
}

int main()
{

    int n = 6;

    vector<stringunsorted = {"31415926535897932384626433832795""1",
                               "3",
                               "10",
                               "3",
                               "5"};

    vector<stringresult = bigSorting(unsorted);

    for (int i = 0i < result.size(); i++)
    {
        cout << result[i];

        if (i != result.size() - 1)
        {
            cout << "\n";
        }
    }
    cout << "\n";

    return 0;
}

Approach: Using Java 8 comparator

Java


import java.util.Arrays;
import java.util.Comparator;

public class BigSorting {
    public static void main(String[] args) {
        String[] unsorted = { "31415926535897932384626433832795""1""3""10""3""5" };
        String[] result = bigSortingJava8(unsorted);
        System.out.println(Arrays.toString(result));
    }


    private static String[] bigSortingJava8(String[] unsorted) {

        Arrays.sort(unsorted,
                (x, y) -> x.length() == y.length() ? x.compareTo(y) : Integer.compare(x.length(), y.length()));
        return unsorted;

    }

}


No comments:

Post a Comment