Varun Hegde
Varun Hegde

Reputation: 135

Sorting numbers digit wise

I have N numbers and I want to sort each number by digit. ( In my original problem I want to make the largest number by these (greedy approach)) For ex - If we have 5 numbers 9 1000 845 8000 56 In first step I will pick 9 as 9 is the highest of all 1st digit of numbers

In second step ( as 9 is already picked), next highest first digit is 8, but when 2 or more numbers have same digit I will compare their next digit so I will pick 845.

In this if I sort I will get the following result 9 845 8000 56 1000.

My question is how can implement this in c++ ?

Thanks in advance

Upvotes: 0

Views: 623

Answers (1)

Masudur Rahman
Masudur Rahman

Reputation: 1693

You can get the expected result by passing a custom compare function to the sort function.

The compare function may be like this:

bool compare(int a, int b) {
    ostringstream x, y;
    x << a; y << b;
    return x.str() > y.str();
}


...
    sort(array, array+n, compare);
...

In this compare function, we are converting the integer data to string data and simply comparing the string values to get the expected sorted array.

Upvotes: 0

Related Questions