0

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

2
  • 2
    Convert the numbers to strings, then sort the strings? Commented Apr 28, 2020 at 13:11
  • Is it correct that in your sorting, 0 is after 4? Because that calls for a complete custom compare, as in numeric as well as lexicographic order, 0 < 4... Commented Jul 20, 2020 at 11:30

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

One liner: std::sort(std::begin(array), std::end(array), [](int lhs, int rhs){ return std::to_string(lhs) > std::to_string(rhs); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.