0

I have an array of nearly sorted ~1000 objects like {val: N} and sorting them by built-in 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:

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.

Where to dig?

Thanks in advance.

1
  • lol! the performance numbers in jsperf.com/javascript-sort/16 are for a sorted array, for which this algorithm (unsurprisingly) takes linear time, instead of its well-known O(N^2) performance... Commented Jan 14, 2013 at 14:21

1 Answer 1

1

You are missing a bounds check on j in the loop:

while (j > 0 && arr[j-1].val > tmp.val) {
    arr[j] = arr[j-1];
    --j;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.