Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 55 additions & 39 deletions sorts/stooge_sort.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,55 @@
def stooge_sort(arr: list[int]) -> list[int]:
"""
Examples:
>>> stooge_sort([18.1, 0, -7.1, -1, 2, 2])
[-7.1, -1, 0, 2, 2, 18.1]

>>> stooge_sort([])
[]
"""
stooge(arr, 0, len(arr) - 1)
return arr


def stooge(arr: list[int], i: int, h: int) -> None:
if i >= h:
return

# If first element is smaller than the last then swap them
if arr[i] > arr[h]:
arr[i], arr[h] = arr[h], arr[i]

# If there are more than 2 elements in the array
if h - i + 1 > 2:
t = (int)((h - i + 1) / 3)

# Recursively sort first 2/3 elements
stooge(arr, i, (h - t))

# Recursively sort last 2/3 elements
stooge(arr, i + t, (h))

# Recursively sort first 2/3 elements
stooge(arr, i, (h - t))


if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(stooge_sort(unsorted))
"""
Stooge Sort - a recursive sorting algorithm.

It is notably slow (worse than bubble sort) but is included here
for educational purposes to illustrate recursive divide-and-conquer thinking.

Time Complexity: O(n^(log3/log1.5)) ≈ O(n^2.71)
Space Complexity: O(log n) due to recursion stack

Reference: https://en.wikipedia.org/wiki/Stooge_sort
"""


def stooge_sort(arr: list[int], i: int = 0, j: int = -1) -> list[int]:
"""
Sorts a list in-place using the stooge sort algorithm and returns it.

>>> stooge_sort([3, 1, 2])
[1, 2, 3]
>>> stooge_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> stooge_sort([1])
[1]
>>> stooge_sort([])
[]
>>> stooge_sort([2, 2, 1])
[1, 2, 2]
>>> stooge_sort([10, -1, 5, 0])
[-1, 0, 5, 10]
"""
if len(arr) <= 1:
return arr

if j == -1:
j = len(arr) - 1

if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]

if (j - i + 1) > 2:
t = (j - i + 1) // 3
stooge_sort(arr, i, j - t)
stooge_sort(arr, i + t, j)
stooge_sort(arr, i, j - t)

return arr


if __name__ == "__main__":
import doctest

doctest.testmod()
user_input = input("Enter numbers separated by commas: ")
nums = [int(x.strip()) for x in user_input.split(",")]
print(f"Sorted: {stooge_sort(nums)}")