Library Sort

Gapped insertion sort.

Best O(n) Avg O(n log n) Worst O(n^2) Space O(n) Stable Yes In-place No Comparison-based

How it works

Gapped insertion sort.

Implementation

function librarySort(arr) {
  const n = arr.length;
  const gaps = new Array(2 * n + 1).fill(null);
  gaps[1] = arr[0];
  let gLen = 1;
  for (let i = 1; i < n; i++) {
    // Binary search in gapped array
    let pos = binarySearch(gaps, gLen, arr[i]);
    insert(gaps, pos, arr[i]);
    gLen++;
    if (gLen >= gaps.length / 2) rebalance(gaps);
  }
  // Compact gaps back into arr
}