If I have the following array: [5, 1, -7, 3, 6, 8, 0, -1, -3]
By sorting it I get [-7, -3, -1, 0, 1, 3, 5, 6, 8]
That’s fine, but what I want is the keys for the array when sorted.
This: [2, 8, 7, 6, 1, 3, 0, 4, 5]
I tried the following using insertion sort, but of course this is wrong.
var arr = [5, 1, -7, 3, 6, 8, 0, -1, -3];
keys = new Array(arr.length);
for(var j = 1; j < arr.length; j++) {
key = arr[j];
var i = j - 1;
while(i >= 0 && arr[i] > key) {
keys[i+1] = i;
i--;
}
arr[i+1] = key;
keys[i+1] = j;
}
Am I on the right track? Can you help me out here 🙂
Try the kind of thing described on this page
http://www.webdotdev.com/nvd/content/view/878/.
Basically, make each item in the array an object with two properties (the sort-key and its index in the array), then sort them by the key.