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
public List<int> SortedIndexOrder(List<int> values) {
}
Worked examples
| Call | Result |
|---|---|
SortedIndexOrder(new List<int> { 40, 10, 30, 10 }) | new List<int> { 1, 3, 2, 0 } |
SortedIndexOrder(new List<int> { 20, 10, 30, 10 }) | new List<int> { 1, 3, 0, 2 } |
SortedIndexOrder(new List<int> { 1, 2, 3 }) | new List<int> { 0, 1, 2 } |
SortedIndexOrder(new List<int> { 3, 2, 1 }) | new List<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#
public List<int> SortedIndexOrder(List<int> values) {
var idx = new List<int>();
for (int i = 0; i < values.Count; i++) idx.Add(i);
idx.Sort((a, b) => {
int d = values[a] - values[b];
return d != 0 ? d : a - b;
});
return idx;
}