Smoothsort

A variation of heapsort.

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

How it works

A variation of heapsort.

Implementation

function smoothSort(arr) {
  const leo = [1, 1];
  while (leo[leo.length-1] < arr.length)
    leo.push(leo.at(-1) + leo.at(-2) + 1);
  let heap = [];  // track Leonardo tree sizes
  for (let i = 0; i < arr.length; i++) {
    // Add element to Leonardo heap
    if (heap.length >= 2 && heap.at(-1) === heap.at(-2) + 1)
      heap[heap.length - 2]++, heap.pop();
    else heap.push(1);
    siftDown(arr, i, heap);
  }
  for (let i = arr.length - 1; i > 0; i--) {
    // Dequeue phase: shrink heap, sift
    if (heap.at(-1) <= 1) heap.pop();
    else { let k = heap.pop();
      heap.push(k - 1, k - 2); siftDown(arr, i, heap); }
  }
}