From 8f93472071606e5f8be52977609e67ab7e4bf856 Mon Sep 17 00:00:00 2001 From: Tommi Laivamaa Date: Sun, 4 Dec 2016 17:00:20 +0200 Subject: [PATCH] Added implementations of gnome sort and cocktail shaker sort --- sorts/cocktail_shaker_sort.py | 36 +++++++++++++++++++++++++++++++++++ sorts/gnome_sort.py | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 sorts/cocktail_shaker_sort.py create mode 100644 sorts/gnome_sort.py diff --git a/sorts/cocktail_shaker_sort.py b/sorts/cocktail_shaker_sort.py new file mode 100644 index 000000000..a21224632 --- /dev/null +++ b/sorts/cocktail_shaker_sort.py @@ -0,0 +1,36 @@ +from __future__ import print_function + +def cocktail_shaker_sort(unsorted): + """ + Pure implementation of the cocktail shaker sort algorithm in Python. + """ + for i in range(len(unsorted)-1, 0, -1): + swapped = False + + for j in range(i, 0, -1): + if unsorted[j] < unsorted[j-1]: + unsorted[j], unsorted[j-1] = unsorted[j-1], unsorted[j] + swapped = True + + for j in range(i): + if unsorted[j] > unsorted[j+1]: + unsorted[j], unsorted[j+1] = unsorted[j+1], unsorted[j] + swapped = True + + if not swapped: + return unsorted + +if __name__ == '__main__': + import sys + + # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin + # otherwise 2.x's input builtin function is too "smart" + if sys.version_info.major < 3: + input_function = raw_input + else: + input_function = input + + user_input = input_function('Enter numbers separated by a comma:\n') + unsorted = [int(item) for item in user_input.split(',')] + cocktail_shaker_sort(unsorted) + print(unsorted) \ No newline at end of file diff --git a/sorts/gnome_sort.py b/sorts/gnome_sort.py new file mode 100644 index 000000000..b353e31aa --- /dev/null +++ b/sorts/gnome_sort.py @@ -0,0 +1,34 @@ +from __future__ import print_function + +def gnome_sort(unsorted): + """ + Pure implementation of the gnome sort algorithm in Python. + """ + if len(unsorted) <= 1: + return unsorted + + i = 1 + + while i < len(unsorted): + if unsorted[i-1] <= unsorted[i]: + i += 1 + else: + unsorted[i-1], unsorted[i] = unsorted[i], unsorted[i-1] + i -= 1 + if (i == 0): + i = 1 + +if __name__ == '__main__': + import sys + + # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin + # otherwise 2.x's input builtin function is too "smart" + if sys.version_info.major < 3: + input_function = raw_input + else: + input_function = input + + user_input = input_function('Enter numbers separated by a comma:\n') + unsorted = [int(item) for item in user_input.split(',')] + gnome_sort(unsorted) + print(unsorted) \ No newline at end of file