Implementing Insert Function

前端 未结 5 1691
感情败类
感情败类 2020-12-11 17:40

I am currently working through Khan Academy\'s algorithm course, which uses JS to teach fundamental algorithms. I am currently in the process of implementing an insertion so

5条回答
  •  Happy的楠姐
    2020-12-11 18:18

    From the challenge:

    Although there are many ways to write this function, you should write it in a way that is consistent with the hint code.

    It's strictly checking for this:

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

    So even though these two alternates are correct:

    while(array[rightIndex] > value && rightIndex >= 0) {
        array[rightIndex + 1] = array[rightIndex];
        rightIndex--;
    }
    array[rightIndex + 1] = value;
    

    And especially this almost identical one (switched the middle statement in the for loop):

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

    This one is the answer:

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

    Ironically, it doesn't care about the useless first variable in the hint...

    var ___;
    

提交回复
热议问题