The order that sorts
A report lists items by rank without disturbing the source rows: instead of the values, it wants their positions.
- Return the original positions (counting from zero) that would put the values in ascending order.
- When values are equal, their original-index order is kept.
sortedIndexOrder(values: list<int>) → list<int>
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
std::vector<int> sortedIndexOrder(std::vector<int> values) {
}
Worked examples
| Call | Result |
|---|---|
sortedIndexOrder(std::vector<int>{40, 10, 30, 10}) | std::vector<int>{1, 3, 2, 0} |
sortedIndexOrder(std::vector<int>{20, 10, 30, 10}) | std::vector<int>{1, 3, 0, 2} |
sortedIndexOrder(std::vector<int>{1, 2, 3}) | std::vector<int>{0, 1, 2} |
sortedIndexOrder(std::vector<int>{3, 2, 1}) | std::vector<int>{2, 1, 0} |
Hint
Sort a list of the indices with a comparator that looks the values up, falling back to the index itself on a tie.
Reference solution in C++
std::vector<int> sortedIndexOrder(std::vector<int> values) {
std::vector<int> idx;
for (int i = 0; i < (int) values.size(); i++) idx.push_back(i);
std::sort(idx.begin(), idx.end(), [&](int a, int b) {
if (values[a] != values[b]) return values[a] < values[b];
return a < b;
});
return idx;
}