Skip to content

Commit a68ec8a

Browse files
Adding stooge sort (#697)
* Create stooge_sort.py * Update stooge_sort.py * Update README.md * Update __init__.py * Update test_sort.py * Update stooge_sort.py * Update test_sort.py * Update stooge_sort.py
1 parent 4b5ccf2 commit a68ec8a

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,7 @@ If you want to uninstall algorithms, it is as simple as:
284284
- [selection_sort](algorithms/sort/selection_sort.py)
285285
- [shell_sort](algorithms/sort/shell_sort.py)
286286
- [sort_colors](algorithms/sort/sort_colors.py)
287+
- [stooge_sort](algorithms/sort/stooge_sort.py)
287288
- [top_sort](algorithms/sort/top_sort.py)
288289
- [wiggle_sort](algorithms/sort/wiggle_sort.py)
289290
- [stack](algorithms/stack)

algorithms/sort/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from .top_sort import *
1414
from .bucket_sort import *
1515
from .shell_sort import *
16+
from .stooge_sort import *
1617
from .radix_sort import *
1718
from .gnome_sort import *
1819
from .cocktail_shaker_sort import *

algorithms/sort/stooge_sort.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''
2+
3+
Stooge Sort
4+
Time Complexity : O(n2.709)
5+
Reference: https://www.geeksforgeeks.org/stooge-sort/
6+
7+
'''
8+
9+
10+
11+
def stoogesort(arr, l, h):
12+
if l >= h:
13+
return
14+
15+
# If first element is smaller
16+
# than last, swap them
17+
if arr[l]>arr[h]:
18+
t = arr[l]
19+
arr[l] = arr[h]
20+
arr[h] = t
21+
22+
# If there are more than 2 elements in
23+
# the array
24+
if h-l + 1 > 2:
25+
t = (int)((h-l + 1)/3)
26+
27+
# Recursively sort first 2 / 3 elements
28+
stoogesort(arr, l, (h-t))
29+
30+
# Recursively sort last 2 / 3 elements
31+
stoogesort(arr, l + t, (h))
32+
33+
# Recursively sort first 2 / 3 elements
34+
# again to confirm
35+
stoogesort(arr, l, (h-t))
36+
37+
38+
if __name__ == "__main__":
39+
array = [1,3,64,5,7,8]
40+
n = len(array)
41+
stoogesort(array, 0, n-1)
42+
for i in range(0, n):
43+
print(array[i], end = ' ')

0 commit comments

Comments
 (0)