FlowLab Logo

Odd-Even Sort Visualizer

Speed:
SlowFast
Bars:
520
(10)
195
[0]
146
[1]
153
[2]
159
[3]
187
[4]
170
[5]
87
[6]
115
[7]
145
[8]
46
[9]
Comparing
Swapping
Sorted
Default
Operation Logs
Click "Start Sort" to begin
Algorithm Info
Time Complexity: O(n²) worst and average case
Space Complexity: O(1) - in-place sorting
Stable: Yes
How it works: Variant of bubble sort that compares all odd/even indexed pairs during odd/even phases, continuing until no swaps are made.
Implementation
function oddEvenSort(arr) {
  let isSorted = false;
  while (!isSorted) {
    isSorted = true;
    // Odd indexed pass
    for (let i = 1; i < arr.length - 1; i += 2) {
      if (arr[i] > arr[i + 1]) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
        isSorted = false;
      }
    }
    // Even indexed pass
    for (let i = 0; i < arr.length - 1; i += 2) {
      if (arr[i] > arr[i + 1]) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
        isSorted = false;
      }
    }
  }
  return arr;
}