Cycle Sort

Theoretically optimal in terms of writes. Minimizes the total number of memory writes by rotating elements into their correct positions.

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

How it works

Theoretically optimal in terms of writes. Minimizes the total number of memory writes by rotating elements into their correct positions.

Implementation

function cycleSort(arr, stats) {
  const n = arr.length;
  for (let cycleStart = 0; cycleStart < n - 1; cycleStart++) {
    let item = arr[cycleStart];
    let pos = cycleStart;
    for (let i = cycleStart + 1; i < n; i++) {
      if (arr[i] < item) pos++;
    }
    if (pos === cycleStart) continue;
    while (item === arr[pos]) {
      pos++;
    }
    if (pos !== cycleStart) {
      [arr[pos], item] = [item, arr[pos]];
      swap(pos, cycleStart);
    }
    while (pos !== cycleStart) {
      pos = cycleStart;
      for (let i = cycleStart + 1; i < n; i++) {
        if (arr[i] < item) pos++;
      }
      while (item === arr[pos]) {
        pos++;
      }
      if (item !== arr[pos]) {
        [arr[pos], item] = [item, arr[pos]];
        swap(pos, cycleStart);
      }
    }
    checkpoint(cycleStart, n - 1);
  }
}