Search code examples
javascriptinsertion-sortkhan-academy

Khan Academy - Challenge: Implement insertion sort


I'm taking a Algorithm class Khan Academy for JavaScript. I wrote a code like this:

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

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

    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]);

And now I wanna know what's wrong here, that I can't get into the next level ... Please help. :)


Solution

  • The problem wasn't that you were giving a wrong answer, it's that you weren't giving the coding solution they were expecting.

    On this particular problem, there's a "hint" section in the upper right hand corner. If you click on the What's this? link.

    This hint shows the code you'll need to successfully complete this step, but it is not the complete answer. The empty blanks are parts that you will need to figure out yourself. If you see colored blanks, the values you put in two blanks of the same color must be exactly the same

    In their hint, they were expecting the same value be used for the initial var, the for loop and the array. Example: substitute for foo.

    var foo;
    for(foo = -----; -----; ----){
        array[foo + 1] = -----;
    }
    ----;
    

    The original poster already showed the Khan Academy solution (shown below). Which doesn't match their hint. shrug This code came from a later exercise which included the insert solution.

    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; 
    };