Drop-Merge Sort

Adaptive based on drops.

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

How it works

Adaptive based on drops.

Implementation

function dropMergeSort(arr, stats) {
  const n = arr.length;
  if (n < 2) return;
  let inc = [0];
  for (let i = 1; i < n; i++) {
    if (arr[i] >= arr[inc[inc.length - 1]]) inc.push(i);
  }
  let incSet = new Set(inc);
  let dropped = [];
  let keptValues = inc.map(idx => arr[idx]);
  for (let i = 0; i < n; i++) {
    if (!incSet.has(i)) {
      dropped.push(arr[i]);
      arr[i] = -1;
      write(i, -1);
    }
  }
  for (let i = 1; i < dropped.length; i++) {
    let key = dropped[i], j = i - 1;
    while (j >= 0 && dropped[j] > key) {
      dropped[j + 1] = dropped[j];
      j--;
    }
    dropped[j + 1] = key;
  }
  let a = 0, b = 0, k = 0;
  while (a < keptValues.length && b < dropped.length) {
    if (keptValues[a] <= dropped[b]) {
      arr[k++] = keptValues[a++];
    } else {
      arr[k++] = dropped[b++];
    }
    write(k - 1, arr[k - 1]);
  }
  while (a < keptValues.length) {
    arr[k++] = keptValues[a++];
    write(k - 1, arr[k - 1]);
  }
  while (b < dropped.length) {
    arr[k++] = dropped[b++];
    write(k - 1, arr[k - 1]);
  }
  for (let i = 0; i < n; i++) markSorted(i);
}