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) {
  for (let cs = 0; cs < arr.length - 1; cs++) {
    let item = arr[cs], pos = cs;
    for (let i = cs+1; i < arr.length; i++)
      if (arr[i] < item) pos++;
    if (pos === cs) continue;
    while (item === arr[pos]) pos++;
    [arr[pos], item] = [item, arr[pos]];
    while (pos !== cs) {
      pos = cs;
      for (let i = cs+1; i < arr.length; i++)
        if (arr[i] < item) pos++;
      while (item === arr[pos]) pos++;
      [arr[pos], item] = [item, arr[pos]];
    }
  }
}