I'm writing the Insertion Sort algorithm in JavaScript.
I have a small bug, however, as follows:
function insertionSort(arrayOfNumbers) {
var j, key, i, length
for (j = 1, length = arrayOfNumbers.length; j < length; j++) {
key = arrayOfNumbers[j]
i = j - 1
while (i >= 0 && arrayOfNumbers[i] > key) {
arrayOfNumbers[i + 1] = arrayOfNumbers[i];
i = i - 1
}
arrayOfNumbers[i + 1] = key
}
return arrayOfNumbers
}
alert(insertionSort([2, 1, 5, 8, 9]))
I've written up the pseudo code version of the algorithm as follow:
for j <- 2 to n
do key <- A[ j ]
i <- j - 1
while i > 0 and A[ i ] > key
do A[ i + 1 ] <- A[ i ]
i <- i - 1
A[ i + 1 ] <- key
Can you spot my error?