What is wrong with my JavaScript sort code?

Viewed 56

I'm learning insertion sort algorithms, and I tried to write a JavaScript program to sort an array in an ascending order using insertion sort method, but there seems to be something wrong with my code as it is not working.

function sortArr(arr){
   for(i=1; i<arr.length; i++){
      let current = arr[i];
      let j = i-1;

      while(j>=0 && arr[j]>current){
         let temp = arr[j+1];
         arr[j+1] = arr[j];
         arr[j] = temp;
         j--;
      }

      arr[j+1] = current;
   }
   return arr;
}
0 Answers
Related