zoukankan      html  css  js  c++  java
  • [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;
    }

  • 相关阅读:
    弹性盒子
    bzoj4237 稻草人
    bzoj2654 tree
    bzoj4813 [Cqoi2017]小Q的棋盘
    bzoj1014 [JSOI2008]火星人
    bzoj3242 [Noi2013]快餐店
    bzoj4025 二分图
    bzoj3237 [Ahoi2013]连通图
    bzoj3244 [Noi2013]树的计数
    bzoj2431 [HAOI2009]逆序对数列
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9470725.html
Copyright © 2011-2022 走看看