2019-09-26 15:19:01 +00:00
|
|
|
def stooge_sort(arr):
|
|
|
|
"""
|
|
|
|
>>> arr = [2, 4, 5, 3, 1]
|
|
|
|
>>> stooge_sort(arr)
|
|
|
|
>>> print(arr)
|
|
|
|
[1, 2, 3, 4, 5]
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
stooge(arr, 0, len(arr) - 1)
|
2019-09-26 15:19:01 +00:00
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
def stooge(arr, i, h):
|
2019-09-26 15:19:01 +00:00
|
|
|
|
|
|
|
if i >= h:
|
|
|
|
return
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-09-26 15:19:01 +00:00
|
|
|
# If first element is smaller than the last then swap them
|
2019-10-05 05:14:13 +00:00
|
|
|
if arr[i] > arr[h]:
|
2019-09-26 15:19:01 +00:00
|
|
|
arr[i], arr[h] = arr[h], arr[i]
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-09-26 15:19:01 +00:00
|
|
|
# If there are more than 2 elements in the array
|
2019-10-05 05:14:13 +00:00
|
|
|
if h - i + 1 > 2:
|
|
|
|
t = (int)((h - i + 1) / 3)
|
|
|
|
|
2019-09-26 15:19:01 +00:00
|
|
|
# Recursively sort first 2/3 elements
|
2019-10-05 05:14:13 +00:00
|
|
|
stooge(arr, i, (h - t))
|
|
|
|
|
2019-09-26 15:19:01 +00:00
|
|
|
# Recursively sort last 2/3 elements
|
2019-10-05 05:14:13 +00:00
|
|
|
stooge(arr, i + t, (h))
|
2019-09-26 15:19:01 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
# Recursively sort first 2/3 elements
|
|
|
|
stooge(arr, i, (h - t))
|