实现插入函数 [英] Implementing Insert Function

查看:181
本文介绍了实现插入函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Khan Academy的算法课程,该课程使用JS来教授基本算法。我目前正在实现插入排序,但发现了一个问题。

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

此工作正常,并按预期执行,但它没有通过KA的自动标记系统。他们给出了代码的指导原则并建议如下:

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?

推荐答案

我有一个与你类似的解决方案,并没有通过他们的自动化测试。如果你稍后看挑战:实施插入排序,他们实际上会继续为你实现这个功能:

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

顺便说一句,你不需要在for循环之前声明j的原因(是之后使用)因为JavaScript没有块范围(TIL):见这里

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

这篇关于实现插入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆