简体   繁体   English

插入对象的排序数组

[英]Insert Sort array of objects

I have an array of nearly sorted ~1000 objects like {val: N} and sorting them by built-in Array.prototype.sort : 我有一个几乎排序的〜1000个对象数组,例如{val: N} ,并通过内置的Array.prototype.sort对其进行排序:

arr.sort(function(a, b) { return a.val - b.val });

I've stumble upon http://jsperf.com/javascript-sort/16 and tried to use Insert Sort: 我偶然发现http://jsperf.com/javascript-sort/16并尝试使用插入排序:

for (i = 1; i < arr.length; i++) {
    var tmp = arr[i],
    j = i;
    while (arr[j-1].val > tmp.val) {
        arr[j] = arr[j-1];
        --j;
    }
    arr[j] = tmp;
}

but it always throws an error: TypeError: Cannot read property 'kills' of undefined . 但它总是引发错误: TypeError: Cannot read property 'kills' of undefined

Where to dig? 在哪里挖?

Thanks in advance. 提前致谢。

You are missing a bounds check on j in the loop: 您在循环中缺少对j的边界检查:

while (j > 0 && arr[j-1].val > tmp.val) {
    arr[j] = arr[j-1];
    --j;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM