mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-18 16:27:02 +00:00
Adding stooge sort (#1206)
* Adding stooge sort * Updated doctest * Just added underscore in the name
This commit is contained in:
parent
6ac7b1387f
commit
2375bfbee5
34
sorts/stooge_sort.py
Normal file
34
sorts/stooge_sort.py
Normal file
|
@ -0,0 +1,34 @@
|
|||
def stooge_sort(arr):
|
||||
"""
|
||||
>>> arr = [2, 4, 5, 3, 1]
|
||||
>>> stooge_sort(arr)
|
||||
>>> print(arr)
|
||||
[1, 2, 3, 4, 5]
|
||||
"""
|
||||
stooge(arr,0,len(arr)-1)
|
||||
|
||||
|
||||
def stooge(arr, i, h):
|
||||
|
||||
|
||||
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))
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user