0

enter image description here

I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insertion-sort. So far I have:

var insert = function(array, rightIndex, value) {
for(var j = rightIndex;
    j >= 0 && array[j] > value;
    j--) {
    array[j + 1] = array[j];
}   
array[j + 1] = value; 
};

var insertionSort = function(array) {

for(var i= 1;  i < array.length ; i++ ) {
    insert(array, i ,array[i+1] );
}

};

var array = [22, 11, 99, 88, 9, 7, 42];
insertionSort(array);

You can see the line of code in the screenshot which appears to be the problem , but it looks fine to me. What am I doing wrong?

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • What is the error you get? – oguzhancerit Jun 07 '17 at 11:55
  • Instead of looping over the array length (since you are constantly adding items to it), loop over a copy: `var insertionSort = function(array) { var copy = array.slice(); for(var i= 0; i < copy.length ; i++ ) { insert(array, i ,array[i+1] ); } };` – Gorka Hernandez Jun 07 '17 at 11:56

1 Answers1

1

You’re starting rightIndex off at i and moving the value array[i + 1], but i reaches array.length and insert starts by setting the element at rightIndex + 1. This will cause the array to grow.

Move the current element and start at the previous index instead:

for (var i = 1; i < array.length; i++) {
    insert(array, i - 1,array[i]);
}

One way to catch this when debugging is to seal your array so it can’t grow:

var array = Object.seal([22, 11, 99, 88, 9, 7, 42]);

This only works in strict mode, though. If you’re in sloppy mode, it will just hide mistakes.

Ry-
  • 218,210
  • 55
  • 464
  • 476