A variation of bubble sort that alternates between comparing odd-even and even-odd index pairs.
Odd-even sort, also called brick sort, is a variation of bubble sort that separates comparisons into two alternating phases. One phase compares elements at odd-even index pairs, and the other compares even-odd pairs.
This structure makes the algorithm suitable for parallel execution, since comparisons within each phase do not overlap.
Problem
Given a sequence of length , reorder it such that
Algorithm
Alternate between two passes:
- Odd phase: compare
- Even phase: compare
Repeat until no swaps occur.
odd_even_sort(A):
n = length(A)
sorted = false
while sorted == false:
sorted = true
# even phase
for i from 0 to n - 2 step 2:
if A[i] > A[i + 1]:
swap(A[i], A[i + 1])
sorted = false
# odd phase
for i from 1 to n - 2 step 2:
if A[i] > A[i + 1]:
swap(A[i], A[i + 1])
sorted = falseExample
Let
Even phase:
| pair | result |
|---|---|
| (5,3) | [3,5,2,4,1] |
| (2,4) | [3,5,2,4,1] |
Odd phase:
| pair | result |
|---|---|
| (5,2) | [3,2,5,4,1] |
| (4,1) | [3,2,5,1,4] |
Continue until sorted:
Correctness
Each phase performs local corrections on disjoint adjacent pairs. Repeated alternation ensures that all inversions are eventually removed. Since the number of inversions strictly decreases when swaps occur, the algorithm converges to a sorted sequence.
Complexity
| case | comparisons | time |
|---|---|---|
| best | ||
| worst | ||
| average |
Space complexity:
Properties
- stable
- in-place
- parallelizable per phase
When to Use
This algorithm is useful in parallel or distributed systems where comparisons can be executed simultaneously in each phase. In sequential settings, it offers no advantage over bubble sort.
Implementation
def odd_even_sort(a):
n = len(a)
sorted_flag = False
while not sorted_flag:
sorted_flag = True
for i in range(0, n - 1, 2):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
sorted_flag = False
for i in range(1, n - 1, 2):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
sorted_flag = False
return afunc OddEvenSort[T constraints.Ordered](a []T) {
n := len(a)
sorted := false
for !sorted {
sorted = true
for i := 0; i < n-1; i += 2 {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
sorted = false
}
}
for i := 1; i < n-1; i += 2 {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
sorted = false
}
}
}
}