diff --git a/README.md b/README.md index e38640143..54f6c6a44 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,7 @@ If you want to uninstall algorithms, it is as simple as: - [selection_sort](algorithms/sort/selection_sort.py) - [shell_sort](algorithms/sort/shell_sort.py) - [sort_colors](algorithms/sort/sort_colors.py) + - [stooge_sort](algorithms/sort/stooge_sort.py) - [top_sort](algorithms/sort/top_sort.py) - [wiggle_sort](algorithms/sort/wiggle_sort.py) - [stack](algorithms/stack) diff --git a/algorithms/sort/__init__.py b/algorithms/sort/__init__.py index fceb3bd22..5a870feff 100644 --- a/algorithms/sort/__init__.py +++ b/algorithms/sort/__init__.py @@ -13,6 +13,7 @@ from .top_sort import * from .bucket_sort import * from .shell_sort import * +from .stooge_sort import * from .radix_sort import * from .gnome_sort import * from .cocktail_shaker_sort import * diff --git a/algorithms/sort/stooge_sort.py b/algorithms/sort/stooge_sort.py new file mode 100644 index 000000000..42f8b3bd4 --- /dev/null +++ b/algorithms/sort/stooge_sort.py @@ -0,0 +1,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 = ' ')