[Algorithms] Insertion sort algorithm using TypeScript

Insertion sort is a very intuitive algorithm as humans use this pattern naturally when sorting cards in our hands.

In this lesson, using TypeScript / Javascript, we’ll cover how to implement this algorithm, why this algorithm gets its name, and the complexity of our implementation of the insertion algorithm.

 

/**
 * ary: [4,3,2,1]
 * 
 * i = 1: 
 * current 3
 * j = 0 --> array[j + 1] = array[j] --> [4, 4]
 * j = -1 --> array[j + 1] = current -->[3, 4]
 * 
 * i = 2: 
 * current: 2
 * j = 1 --> array[j + 1] = array[j] --> [3,4,4]
 * j = 0 --> array[j + 1] = array[j] --> [3,3,4]
 * j = -1 --> array[j + 1] = current --> [2,3,4]
 */

 

function insertionSort(ary) {
  let array = ary.slice();

  for (let i = 1; i < array.length; i++) {
    let current = array[i];
    let j = i - 1;
    while (j >= 0 && array[j] > current) {
      // move the j to j+1
      array[j + 1] = array[j];
      j--;
    }
    // j = -1
    array[j + 1] = current;
  }
  return array;
}

 

 

posted @ 2018-08-13 20:29  Zhentiw  阅读(227)  评论(0编辑  收藏  举报