Implementation of the insert function

I am currently working through the Han Academy Algorithm Course, which uses JS to teach fundamental algorithms. I am currently sorting an insert, but found a problem.

We write a function that takes an array, an index for the beginning, and values ​​to insert the number into the correct ordered position. I wrote a 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 great and works as it should, but it doesn’t go through the automatic KA marking system. They give recommendations for the code and suggest to do it as such:

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

Does anyone know how I can repeat my code to fit these standards?

+5
source share
4 answers

I had a similar solution, since you did not pass the automated test. If you look later in the section “Task: perform insertion of sorting”, they actually go ahead and implement this 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 (for later use) is because JavaScript does not have a block area (TIL): See Here

+3
source

There is no need to return an array as it is passed by reference. Just slide each item 1 to the right. The last statement simply inserts the value into the correct position.

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

Most of the answers posted here are correct. But this does not give us the next step at Khan Academy. This may be because the Khan Academy expects a specific variable name, indentation settings, etc. I'm not quite sure why this will not lead us to the next step.

This code helped me move on to the next step:

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

Before I discovered this code, I used I as a variable name instead of j, but that did not lead me to the next step. But it is so.

0
source

This worked:

var insert = function (array, rightIndex, value) {

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

Source: https://habr.com/ru/post/1207211/


All Articles