Implement Insertion Sort *

I do not understand what is the reason why this is not working. It works with i=9. But it does not operate with i=10 properly.


function insertionSort(array) {
for(let i=0;i<array.length;i++){
  let temp=array[i];
  for(let j=10;j>i;j--){
    while(array[j]<array[i]){
          array[i]=array[j]
          array[j]=temp    
     }

  }
     
}
console.log(array)
}

insertionSort([7,1,5,4,2,1,11,10,9,5643,1,75]);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36.

Challenge: Implement Insertion Sort

Link to the challenge:

Hi @santiagodeleondecar1 !

It looks like the problem is here.

If i and j are both 10 then 10 is not greater than 10.

1 Like

Thank you very much for your help.

function insertionSort(array) {
    for(let i=0;i<array.length;i++){
      let temp=[]
        for(let j=array.length;i<j;j--){
               while(array[i]>array[j]){
                 temp=array[i]
                array[i]=array[j]
                array[j]=temp  
               }      
        }

    }
    //console.log(array)
  return array;
 
}

insertionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.