Skip to content
大纲

插入排序

js
const arr = [9, 2, 5, 6, 1, 0, 1, 2];

function insertSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    const t = arr[i];
    let preIndex = i - 1;
    while (arr[preIndex] > t) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }
    arr[preIndex + 1] = t;
  }
  console.log(arr);
}

insertSort(arr);

Released under the MIT License.