Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

javascript - Implementing Insert Function

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 sort, but have found a problem.

We are writing a function which takes in an array, index to start from and value, in order to insert a number in the correct ordered position. I have written said function here:

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

This works fine, and performs as it should, however it does not pass KA's automated marking system. They give guidelines for the code and suggest it be done as such:

for(var ____ = _____; ____ >= ____; ____) {
    array[____+1] = ____;
}
____;

Does anyone know how I could reiterate my code to conform to these standards?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had a similar solution as you and didn't pass their automated test. If you look later at "Challenge: Implement insertion sort" they actually go ahead and implement the function for you:

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

As an aside, the reason you don't need to declare j before the for loop (to be used later) is because JavaScript doesn't have block scope (TIL): See here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...