As others have pointed out, a lexicographic sort and concatenation is close, but not quite correct. For example, for the numbers 5, 54, and 56 a lexicographic sort will produce {5, 54, 56} (in increasing order) or {56, 54, 5} (in decreasing order), but what we really want is {56, 5, 54}, since that produces the largest number possible.
So we want a comparator for two numbers that somehow puts the biggest digits first.
- We can do that by comparing individual digits of the two numbers, but we have to be careful when we step off the end of one number if the other number still has remaining digits. There are lots of counters, arithmetic, and edge cases that we have to get right.
A cuter solution (also mentioned by @Sarp Centel) achieves the same result as (1) but with a lot less code. The idea is to compare the concatenation of two numbers with the reverse concatenation of those numbers. All of the cruft that we have to explicitly handle in (1) is handled implicitly.
For example, to compare
56and5, we'd do a regular lexicographic comparison of565to556. Since565>556, we'll say that56is "bigger" than5, and should come first. Similarly, comparing54and5means we'll test545<554, which tells us that5is "bigger" than54.
Here's a simple example:
// C++0x: compile with g++ -std=c++0x <filename> #include <iostream> #include <string> #include <algorithm> #include <vector> int main() { std::vector<std::string> v = { "95", "96", "9", "54", "56", "5", "55", "556", "554", "1", "2", "3" }; std::sort(v.begin(), v.end(), [](const std::string &lhs, const std::string &rhs) { // reverse the order of comparison to sort in descending order, // otherwise we'll get the "big" numbers at the end of the vector return rhs+lhs < lhs+rhs; }); for (size_t i = 0; i < v.size(); ++i) { std::cout << v[i] << ' '; } }Read full article from algorithm - How can I manipulate an array to make the largest number? - Stack Overflow
No comments:
Post a Comment