0

enter image description here

I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insert .

After calling the insert function: * value and the elements that were previously in array[0] to array[rightIndex], should be sorted in ascending order and stored in the elements from array[0] to array[rightIndex+1]. In order to do this, the insert function will need to make room for value by moving items that are greater than value to the right. It should start at rightIndex, and stop when it finds an item that is less than or equal to value, or when it reaches the beginning of the array. Once the function has made room for value, it can write value to the array.

My attempt is:

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

var i = rightIndex;
    for( array[i]> key ; 0; i-- ) {

        array[i + 1] = array[i]; 
   } 
   array[i]= value;

};

var array = [3, 5, 7, 11, 13, 2, 9, 6];

insert(array, 4, 2);
println("Array after inserting 2:  " + array);

They specifically say they want a condition within the for loop, but I don't know how to do that.

user1592380
  • 34,265
  • 92
  • 284
  • 515

1 Answers1

2
 var insert = function(array, rightIndex, value) {
    // for( initial_value; condition; change the value for next iteration)
    // && - returns true only when both are true.
     for(var j = rightIndex; j >= 0 && array[j] > value; j--) {
        array[j + 1] = array[j];
    }
    array[j + 1] = value; 

};
Prakash N
  • 1,020
  • 1
  • 8
  • 20
Monkey_Dev1400
  • 924
  • 6
  • 14
  • Can you explain what this challenge is asking for? I've read this algo problem like 100 times and it still makes no sense. What is the purpose of rightIndex? It's like a drunk person wrote this. – JellyKid Jun 06 '17 at 19:58
  • 1
    haha. it's basically saying you want to insert a number into the array, so what you want is to check 'value' and compare that number to all the numbers within the array. Once it gets to a number that is greater than your 'value' then it stops and insert itself into the array. The purpose of the rightIndex is to start at rightIndex, and stop when it finds an item that is less than or equal to value. – Monkey_Dev1400 Jun 06 '17 at 20:08
  • Thank you, I didn't know you could do that in js – user1592380 Jun 06 '17 at 20:24