Insertion sort

2022.6.17
Dev

平均計算時間: O(n^2)

安定ソート

JavaScriptによる実装

function insertionSort(a) {
  for (let i = 1; i < a.length; i++) {
    let x = a[i];
    let j = i - 1;
  
    while (j >= 0 && a[j] > x) {
      a[j + 1] = a[j];
      j--;
    }
  
    a[j + 1] = x;
  }
}

const a = [7, 15, 1, 8, 11, 5, 13, 0, 2, 4, 6, 3, 12, 14, 9, 10];
insertionSort(a);

console.log(a);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]