A recursive sorting algorithm with extremely poor performance based on overlapping subproblems.
Stooge sort is a recursive sorting algorithm with very poor efficiency. It repeatedly sorts overlapping parts of the array. The algorithm has theoretical interest but no practical use.
Problem
Given a sequence of length , reorder it such that
Algorithm
For a subarray :
If the first element is greater than the last, swap them
If the size is greater than 2, recursively sort:
- the first of the array
- the last of the array
- the first again
stooge_sort(A, l, r):
if A[l] > A[r]:
swap(A[l], A[r])
if r - l + 1 > 2:
t = (r - l + 1) // 3
stooge_sort(A, l, r - t)
stooge_sort(A, l + t, r)
stooge_sort(A, l, r - t)Example
Let
Step 1:
Swap first and last if needed → no change
Recursive calls:
- sort first 2 elements → [1,2,3]
- sort last 2 elements → [1,2,3]
- sort first 2 elements again
Final result:
Correctness
The recursive structure ensures that elements are repeatedly compared and corrected across overlapping regions. Over time, all inversions are eliminated. However, this process is highly redundant.
Complexity
The recurrence is:
This solves to:
This is worse than .
Space complexity:
due to recursion depth.
Properties
- in-place
- not stable
- extremely inefficient
- overlapping recursive structure
When to Use
Stooge sort has no practical use. It is studied as an example of inefficient recursion and as a contrast to efficient divide-and-conquer algorithms.
Implementation
def stooge_sort(a, l, r):
if a[l] > a[r]:
a[l], a[r] = a[r], a[l]
if r - l + 1 > 2:
t = (r - l + 1) // 3
stooge_sort(a, l, r - t)
stooge_sort(a, l + t, r)
stooge_sort(a, l, r - t)func StoogeSort[T constraints.Ordered](a []T, l, r int) {
if a[l] > a[r] {
a[l], a[r] = a[r], a[l]
}
if r-l+1 > 2 {
t := (r - l + 1) / 3
StoogeSort(a, l, r-t)
StoogeSort(a, l+t, r)
StoogeSort(a, l, r-t)
}
}