Insert Sort - 401-advanced-javascript-hanna-alemu/seattle-javascript-401d31 GitHub Wiki

What is the Insert Sort algorithm?

This is the starter pseudo-code that is written in Java.

``InsertionSort(int[] arr) FOR i = 1 to arr.length

  int j <-- i - 1
  int temp <-- arr[i]
  
  WHILE j >= 0 AND temp < arr[j]
    arr[j + 1] <-- arr[j]
    j <-- j - 1
    
  arr[j + 1] <-- temp``

Here is the code that I converted into Javascript.

``function insertSort (array) { for(let i = 1; i < array.length; i++) {

let j = i - 1;
let temp = array[i];

while(j >= 0 && temp < array[j] ) {
  array[j + 1 ] = array[j];
  j = j - 1;
}
array[j + 1] = temp;

} return array; }``

So how does the code work?

The algorithm works according to the following steps:-

  1. First, we loop over the array, starting from the second element(at index 1) and keep track of the elements using a temporary variable.
  2. Then we add another variable(j) that's one less than the element being tracked by the for-loop.
  3. Now we compare the two elements and move the lesser element to the left of the larger element.
  4. In the end, we return the array