SOURCE

function insertionSort (arr) {
  let n = arr.length;
  let preIndex, current;
  for (let i = 1; i < n; i++) {
    current = arr[i];
    preIndex = i - 1;
    // 如果前面的比当前的大就向后挪
    while (preIndex >= 0 && arr[preIndex] > current) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }
    // 当前的挪到空出来的位置
    arr[preIndex + 1] = current;
  }
  return arr;
}
var arr = insertionSort([3, 2, 4, 5, 1]);
console.log(arr);
console 命令行工具 X clear

                    
>
console