File tree
Expand file treeCollapse file tree2 files changed
+70
-0
lines changed Expand file treeCollapse file tree2 files changed
+70
-0
lines changed Original file line number | Diff line number | Diff line change |
---|
|
| 1 | +from __future__ import print_function |
| 2 | + |
| 3 | +def cocktail_shaker_sort(unsorted): |
| 4 | +""" |
| 5 | +Pure implementation of the cocktail shaker sort algorithm in Python. |
| 6 | +""" |
| 7 | +for i in range(len(unsorted)-1, 0, -1): |
| 8 | +swapped = False |
| 9 | + |
| 10 | +for j in range(i, 0, -1): |
| 11 | +if unsorted[j] < unsorted[j-1]: |
| 12 | +unsorted[j], unsorted[j-1] = unsorted[j-1], unsorted[j] |
| 13 | +swapped = True |
| 14 | + |
| 15 | +for j in range(i): |
| 16 | +if unsorted[j] > unsorted[j+1]: |
| 17 | +unsorted[j], unsorted[j+1] = unsorted[j+1], unsorted[j] |
| 18 | +swapped = True |
| 19 | + |
| 20 | +if not swapped: |
| 21 | +return unsorted |
| 22 | + |
| 23 | +if __name__ == '__main__': |
| 24 | +import sys |
| 25 | + |
| 26 | +# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin |
| 27 | +# otherwise 2.x's input builtin function is too "smart" |
| 28 | +if sys.version_info.major < 3: |
| 29 | +input_function = raw_input |
| 30 | +else: |
| 31 | +input_function = input |
| 32 | + |
| 33 | +user_input = input_function('Enter numbers separated by a comma:\n') |
| 34 | +unsorted = [int(item) for item in user_input.split(',')] |
| 35 | +cocktail_shaker_sort(unsorted) |
| 36 | +print(unsorted) |
Original file line number | Diff line number | Diff line change |
---|
|
| 1 | +from __future__ import print_function |
| 2 | + |
| 3 | +def gnome_sort(unsorted): |
| 4 | +""" |
| 5 | +Pure implementation of the gnome sort algorithm in Python. |
| 6 | +""" |
| 7 | +if len(unsorted) <= 1: |
| 8 | +return unsorted |
| 9 | + |
| 10 | +i = 1 |
| 11 | + |
| 12 | +while i < len(unsorted): |
| 13 | +if unsorted[i-1] <= unsorted[i]: |
| 14 | +i += 1 |
| 15 | +else: |
| 16 | +unsorted[i-1], unsorted[i] = unsorted[i], unsorted[i-1] |
| 17 | +i -= 1 |
| 18 | +if (i == 0): |
| 19 | +i = 1 |
| 20 | + |
| 21 | +if __name__ == '__main__': |
| 22 | +import sys |
| 23 | + |
| 24 | +# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin |
| 25 | +# otherwise 2.x's input builtin function is too "smart" |
| 26 | +if sys.version_info.major < 3: |
| 27 | +input_function = raw_input |
| 28 | +else: |
| 29 | +input_function = input |
| 30 | + |
| 31 | +user_input = input_function('Enter numbers separated by a comma:\n') |
| 32 | +unsorted = [int(item) for item in user_input.split(',')] |
| 33 | +gnome_sort(unsorted) |
| 34 | +print(unsorted) |
You can’t perform that action at this time.
0 commit comments