I think I am on the verge of solving this but Im not sure why my code is not executing correctly. Can someone provide some feedback for me and show me where I messed up?
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, array.length -1, i);
}
};
var array = [22, 11, 99, 88, 9, 7, 42];
insertionSort(array);
println("Array after sorting: " + array);
//Program.assertEqual(array, [7, 9, 11, 22, 42, 88, 99]);
if I do this insert(array, array[i], i);
,I get the following output:
Array after sorting: 22,11,12,100,89,10,8,43,5,,4,,1,,
I think you have a probleme here:
in
insert(array, array.length -1, i);
it should beinsert(array, array.length -1, array[i]);
you were inserting array index instead of the value
also you have an array out of bound in
array[j + 1] = array[j];
because j start fromarray.length -1
, it should bearray[j] = array[j-1];
whilej>0
last thing: your rightIndex should be i at each iteration not
array.length -1
.Complete code :