Python Program for Stooge Sort (original) (raw)
Last Updated : 20 Jan, 2026
Stooge Sort is a recursive sorting algorithm. It is not efficient for large datasets, but it helps beginners understand recursion and divide-and-conquer techniques. Given an array of numbers, sort it in ascending order using Stooge Sort.
**Example:
**Input: arr = [2, 4, 5, 3, 1]
**Output: arr = [1 2 3 4 5]
How Stooge Sort Works
- Compare the first and last elements of the array. If the first element is greater, swap them.
- If the array has more than two elements:
Recursively sort the first 2/3 of the array.
Recursively sort the last 2/3 of the array.
Recursively sort the first 2/3 again to confirm the middle elements are in place.
Python Implementation
Python `
def stoogesort(arr, l, h): if l >= h: return
if arr[l] > arr[h]:
arr[l], arr[h] = arr[h], arr[l]
if h - l + 1 > 2:
t = (h - l + 1) // 3
stoogesort(arr, l, h - t)
stoogesort(arr, l + t, h)
stoogesort(arr, l, h - t)arr = [2, 4, 5, 3, 1] stoogesort(arr, 0, len(arr) - 1) print("Sorted array:", arr)
`
Output
Sorted array: [1, 2, 3, 4, 5]
**Explanation:
- **if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l]: Swaps first and last elements if they are in the wrong order.
- **t = (h - l + 1) // 3: Calculates one-third of the current array length.
- **stoogesort(arr, l, h - t): Recursively sorts the first two-thirds.
- **stoogesort(arr, l + t, h): Recursively sorts the last two-thirds.
- **stoogesort(arr, l, h - t): Sorts the first two-thirds again to ensure correct order of middle elements.
Please refer complete article on Stooge Sort for more details!