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?
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.