如何获取数组中已排序值的键

时间:2011-07-01 03:09:06

标签: javascript sorting

如果我有以下数组:[5,1,-7,3,6,8,0,-1,-3]

通过排序我得到[-7,-3,-1,0,1,3,5,6,8]

没关系,但我想要的是排序时数组的键。 这:[2,8,7,6,1,3,0,4,5]

我使用插入排序尝试了以下操作,但当然这是错误的。

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;
}

我是否在正确的轨道上?你能帮助我吗:))

3 个答案:

答案 0 :(得分:3)

尝试本页描述的那种东西

http://www.webdotdev.com/nvd/content/view/878/

基本上,将数组中的每个项目作为具有两个属性的对象(数组中的sort-key及其索引),然后按键对它们进行排序。

答案 1 :(得分:3)

您可能不想对数组进行排序,只返回已排序索引的数组 -

var A= [5, 1, -7, 3, 6, 8, 0, -1, -3], i, L=A.length, B=[];

for(i=0;i<L;i++) B[i]=[A[i],i];

B.sort(function(a,b){return a[0]-b[0]});

for(var i=0;i<L;i++)B[i]=B[i].pop();

A+'\n'+ B

返回值:

5,1,-7,3,6,8,0,-1,-3

2,8,7,6,1,3,0,4,5 //排序订单索引

答案 2 :(得分:1)

var arr = [5, 1, -7, 3, 6, 8, 0, -1, -3];

// Create an array that pairs the values with the indices
for (var paired=[],i=0,len=els.length;i<len;++i) paired[i] = [arr[i],i];
// result: [[5,0],[1,1],[-7,2],[3,3],[6,4],[8,5],[0,6],[-1,7],[-3,8]]

// Sort that array by the values (first element)
paired.sort(function(a,b){ a=a[0]; b=b[0]; return a<b?-1:a>b?1:0; });
// result: [[-7,2],[-3,8],[-1,7],[0,6],[1,1],[3,3],[5,0],[6,4],[8,5]]

// Create another array that has just the (now-sorted) indices (second element)
for (var indices=[],i=0;i<len;++i) indices[i] = paired[i][1];
// result: [2, 8, 7, 6, 1, 3, 0, 4, 5]
相关问题