Given an array A of non-negative integers of size m. Your task is to sort the array in non-decreasing order and print out the original indices of the new sorted array. e.g.A={4,5,3,7,1}
After sorting the new array becomes A={1,3,4,5,7}.
The required output should be “4 2 0 1 3”
Advertisement
Answer
You need to pair (tuple) the value with the original index. After mapping the tuples, sort by the value and finally map the original (now sorted) indices.
JavaScript
x
9
1
const sortValuesAndGetOriginalIndices = (arr) => arr
2
.map((element, index) => [element, index])
3
.sort(([v1], [v2]) => v1 - v2)
4
.map(([value, index]) => index);
5
6
const arr = [4, 5, 3, 7, 1];
7
const indices = sortValuesAndGetOriginalIndices(arr);
8
9
console.log(indices); // [4, 2, 0, 1, 3]
If you want to return the sorted values and the indicies, you can reduce at the end:
JavaScript
1
15
15
1
const enhancedSort = (arr) => arr
2
.map((element, index) => [element, index])
3
.sort(([v1], [v2]) => v1 - v2)
4
.reduce(({ values, indices }, [v, i]) =>
5
({
6
values: [values, v],
7
indices: [indices, i]
8
}),
9
{ values: [], indices: [] });
10
11
const arr = [4, 5, 3, 7, 1];
12
const { values, indices } = enhancedSort(arr);
13
14
console.log(values); // [1, 3, 4, 5, 7]
15
console.log(indices); // [4, 2, 0, 1, 3]
JavaScript
1
1
1
.as-console-wrapper { top: 0; max-height: 100% !important; }