forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stooge_sort.py
43 lines (31 loc) · 910 Bytes
/
stooge_sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
'''
Stooge Sort
Time Complexity : O(n2.709)
Reference: https://www.geeksforgeeks.org/stooge-sort/
'''
def stoogesort(arr, l, h):
if l >= h:
return
# If first element is smaller
# than last, swap them
if arr[l]>arr[h]:
t = arr[l]
arr[l] = arr[h]
arr[h] = t
# If there are more than 2 elements in
# the array
if h-l + 1 > 2:
t = (int)((h-l + 1)/3)
# Recursively sort first 2 / 3 elements
stoogesort(arr, l, (h-t))
# Recursively sort last 2 / 3 elements
stoogesort(arr, l + t, (h))
# Recursively sort first 2 / 3 elements
# again to confirm
stoogesort(arr, l, (h-t))
if __name__ == "__main__":
array = [1,3,64,5,7,8]
n = len(array)
stoogesort(array, 0, n-1)
for i in range(0, n):
print(array[i], end = ' ')