Binary Insertion Sort

Insertion sort with binary search for insertion points, reducing comparisons while keeping shifts.

Best O(n) Avg O(n²) Worst O(n²) Space O(1) Stable Yes In-place Yes Comparison-based

How it works

Insertion sort with binary search for insertion points, reducing comparisons while keeping shifts.

Implementation

function binaryInsertionSort(arr, stats) {
  const n = arr.length;
  for (let i = 1; i < n; i++) {
    const key = arr[i];
    let left = 0;
    let right = i;
    while (left < right) {
      const mid = left + right >> 1;
      compare(mid, i);
      if (arr[mid] <= key) left = mid + 1; else right = mid;
    }
    for (let j = i; j > left; j--) {
      arr[j] = arr[j - 1];
      write(j, arr[j]);
    }
    arr[left] = key;
    write(left, key);
  }
}