From cd8404bfdcfc2ae326e5a65cd4d34f448b410f61 Mon Sep 17 00:00:00 2001 From: Sergey Tsaplin Date: Fri, 29 Jul 2016 15:58:23 +0500 Subject: [PATCH 1/9] Make selection sort pythonic way --- SelectionSort.py | 20 ------------------- selection_sort.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 20 deletions(-) delete mode 100644 SelectionSort.py create mode 100644 selection_sort.py diff --git a/SelectionSort.py b/SelectionSort.py deleted file mode 100644 index 6f3b9fe0d..000000000 --- a/SelectionSort.py +++ /dev/null @@ -1,20 +0,0 @@ -def selectionsort( aList ): - for i in range( len( aList ) ): - least = i - for k in range( i + 1 , len( aList ) ): - if aList[k] < aList[least]: - least = k - - aList = swap( aList, least, i ) - print(aList) - -def swap( A, x, y ): - tmp = A[x] - A[x] = A[y] - A[y] = tmp - return A - -print ("Enter numbers seprated by comma ") -response = input() -aList = [int(item) for item in (response.split(','))] -selectionsort(aList) diff --git a/selection_sort.py b/selection_sort.py new file mode 100644 index 000000000..4de19d230 --- /dev/null +++ b/selection_sort.py @@ -0,0 +1,51 @@ +""" +This is pure python implementation of selection sort algorithm + +For doctests run following command: +python -m doctest -v selection_sort.py +or +python3 -m doctest -v selection_sort.py +""" +from __future__ import print_function + +def selection_sort(sortable): + """Pure implementation of selection sort algorithm in Python + + Examples: + >>> selection_sort([0, 5, 3, 2, 2]) + [0, 2, 2, 3, 5] + + >>> selection_sort([]) + [] + + >>> selection_sort([-2, -5, -45]) + [-45, -5, -2] + + :param sortable: some mutable ordered collection with heterogeneous + comparable items inside + :return: the same collection ordered by ascending + """ + length = len(sortable) + for i in range(length): + least = i + for k in range(i + 1, length): + if sortable[k] < sortable[least]: + least = k + sortable[least], sortable[i] = ( + sortable[i], sortable[least] + ) + return sortable + + +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 coma:\n') + unsorted = [int(item) for item in user_input.split(',')] + print(selection_sort(unsorted)) From 7dff214d9ba2bd178830d06422073022def49ba3 Mon Sep 17 00:00:00 2001 From: Sergey Tsaplin Date: Fri, 29 Jul 2016 18:03:20 +0500 Subject: [PATCH 2/9] Binary Search refactoring --- BinarySeach.py | 105 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 76 insertions(+), 29 deletions(-) diff --git a/BinarySeach.py b/BinarySeach.py index 9d09c6ba3..0a00a69f4 100644 --- a/BinarySeach.py +++ b/BinarySeach.py @@ -1,30 +1,77 @@ -def binarySearch(alist, item): - - first = 0 - last = len(alist)-1 - found = False - - while first<=last and not found: - - midpoint = (first + last)//2 - if alist[midpoint] == item: - found = True - print("Found [ at position: %s ]" % (alist.index(item) + 1)) - else: - - if item < alist[midpoint]: - - last = midpoint-1 - else: - first = midpoint+1 - - if found == False: - continue - # print("Not found") - return found -print("Enter numbers seprated by space") -s = input() -numbers = list(map(int, s.split())) -trgt =int( input('enter a single number to be found in the list ')) -binarySearch(numbers, trgt) +""" +This is pure python implementation of binary search algorithm +For doctests run following command: +python -m doctest -v selection_sort.py +or +python3 -m doctest -v selection_sort.py + +For manual testing run: +python binary_search.py +""" +from __future__ import print_function + + +def binary_search(sorted_collection, item): + """Pure implementation of binary sort algorithm in Python + + :param sorted_collection: some sorted collection with comparable items + :param item: item value to search + :return: index of found item or None if item is not found + + Examples: + >>> binary_search([0, 5, 7, 10, 15], 0) + 0 + + >>> binary_search([0, 5, 7, 10, 15], 15) + 4 + + >>> binary_search([0, 5, 7, 10, 15], 5) + 1 + + >>> binary_search([0, 5, 7, 10, 15], 6) + + >>> binary_search([5, 2, 1, 5], 2) + Traceback (most recent call last): + ... + ValueError: Collection must be sorted + """ + if sorted_collection != sorted(sorted_collection): + raise ValueError('Collection must be sorted') + left = 0 + right = len(sorted_collection) - 1 + + while left <= right: + midpoint = (left + right) // 2 + current_item = sorted_collection[midpoint] + if current_item == item: + return midpoint + else: + if item < current_item: + right = midpoint - 1 + else: + left = midpoint + 1 + return None + + +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 coma:\n') + collection = [int(item) for item in user_input.split(',')] + + target_input = input_function( + 'Enter a single number to be found in the list:\n' + ) + target = int(target_input) + result = binary_search(collection, target) + if result is not None: + print('{} found at positions: {}'.format(target, result)) + else: + print('Not found') From 65ca0bbaa2ebf11ec8081598f32c98a23e24d4e3 Mon Sep 17 00:00:00 2001 From: Sergey Tsaplin Date: Fri, 29 Jul 2016 18:06:37 +0500 Subject: [PATCH 3/9] Rename binary_search module pythonic way --- BinarySeach.py => binary_seach.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename BinarySeach.py => binary_seach.py (100%) diff --git a/BinarySeach.py b/binary_seach.py similarity index 100% rename from BinarySeach.py rename to binary_seach.py From ec6b64a9eca8c2d3f092e2e0a44c6b18159a0b54 Mon Sep 17 00:00:00 2001 From: Sergey Tsaplin Date: Fri, 29 Jul 2016 19:12:51 +0500 Subject: [PATCH 4/9] Add bin search algorithm using stdlib --- binary_seach.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/binary_seach.py b/binary_seach.py index 0a00a69f4..a48762863 100644 --- a/binary_seach.py +++ b/binary_seach.py @@ -10,10 +10,32 @@ For manual testing run: python binary_search.py """ from __future__ import print_function +import bisect + + +def assert_sorted(collection): + """Check if collection is sorted. If not raises :py:class:`ValueError` + + :param collection: collection + :return: True if collection is sorted + :raise: :py:class:`ValueError` if collection is not sorted + + Examples: + >>> assert_sorted([0, 1, 2, 4]) + True + + >>> assert_sorted([10, -1, 5]) + Traceback (most recent call last): + ... + ValueError: Collection must be sorted + """ + if collection != sorted(collection): + raise ValueError('Collection must be sorted') + return True def binary_search(sorted_collection, item): - """Pure implementation of binary sort algorithm in Python + """Pure implementation of binary search algorithm in Python :param sorted_collection: some sorted collection with comparable items :param item: item value to search @@ -36,8 +58,7 @@ def binary_search(sorted_collection, item): ... ValueError: Collection must be sorted """ - if sorted_collection != sorted(sorted_collection): - raise ValueError('Collection must be sorted') + assert_sorted(sorted_collection) left = 0 right = len(sorted_collection) - 1 @@ -54,6 +75,37 @@ def binary_search(sorted_collection, item): return None +def binary_search_std_lib(sorted_collection, item): + """Pure implementation of binary search algorithm in Python using stdlib + + :param sorted_collection: some sorted collection with comparable items + :param item: item value to search + :return: index of found item or None if item is not found + + Examples: + >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) + 0 + + >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) + 4 + + >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) + 1 + + >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) + + >>> binary_search_std_lib([5, 2, 1, 5], 2) + Traceback (most recent call last): + ... + ValueError: Collection must be sorted + """ + assert_sorted(sorted_collection) + index = bisect.bisect_left(sorted_collection, item) + if index != len(sorted_collection) and sorted_collection[index] == item: + return index + return None + + if __name__ == '__main__': import sys # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin From 549915acd43bdca3aed47b880a43741fec5bc2f1 Mon Sep 17 00:00:00 2001 From: Tony Sappe Date: Fri, 29 Jul 2016 14:47:32 -0400 Subject: [PATCH 5/9] Made improvements to Bubble and Insertion algorithms * Placed the algorithms within their own functions separate from the input and output code * Updated README --- BubbleSort.py | 47 ++++++++++++++++++++++------------------- InsertionSort.py | 45 ++++++++++++++++++++++------------------ README.md | 54 ++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 103 insertions(+), 43 deletions(-) diff --git a/BubbleSort.py b/BubbleSort.py index 5a0388855..513f788e0 100644 --- a/BubbleSort.py +++ b/BubbleSort.py @@ -1,26 +1,31 @@ -array=[]; - -# input -print ("Enter any 6 Numbers for Unsorted Array : "); -for i in range(0, 6): - n=input(); - array.append(int(n)); - -# Sorting -print("") -for i in range(0, 6): - for j in range(0,5): - if (array[j]>array[j+1]): - temp=array[j]; - array[j]=array[j+1]; - array[j+1]=temp; - -# Output -for i in range(0,6): - print(array[i]); - +def simple_bubble_sort(int_list): + count = len(int_list) + swapped = True + while (swapped): + swapped = False + for j in range(count - 1): + if (int_list[j] > int_list[j + 1]): + int_list[j], int_list[j + 1] = int_list[j + 1], int_list[j] + swapped = True + return int_list +def main(num): + inputs = [] + print("Enter any {} numbers for unsorted list: ".format(num)) + try: + for i in range(num): + n = input() + inputs.append(n) + except Exception as e: + print(e) + else: + sorted_input = simple_bubble_sort(inputs) + print('\nSorted list (min to max): {}'.format(sorted_input)) +if __name__ == '__main__': + print('==== Bubble Sort ====\n') + list_count = 6 + main(list_count) diff --git a/InsertionSort.py b/InsertionSort.py index e0417a755..679d06756 100644 --- a/InsertionSort.py +++ b/InsertionSort.py @@ -1,25 +1,30 @@ -array=[]; -# input -print ("Enter any 6 Numbers for Unsorted Array : "); -for i in range(0, 6): - n=input(); - array.append(int(n)); - -# Sorting -print("") -for i in range(1, 6): - temp=array[i] - j=i-1; - while(j>=0 and temp= 0 and temp < int_list[j]): + int_list[j + 1] = int_list[j] + j -= 1 + int_list[j + 1] = temp + return int_list +def main(num): + inputs = [] + print('Enter any {} numbers for unsorted list: '.format(num)) + try: + for i in range(num): + n = input() + inputs.append(n) + except Exception as e: + print(e) + else: + sorted_input = simple_insertion_sort(inputs) + print('\nSorted list (min to max): {}'.format(sorted_input)) +if __name__ == '__main__': + print('==== Insertion Sort ====\n') + list_count = 6 + main(list_count) diff --git a/README.md b/README.md index 4c8df87ad..de55ae89a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,52 @@ -# Python- -All Algorithms implemented in Python +# The Algoritms - Python + +### **All Algorithms implemented in Python!** + + +## Sorting + + +### Binary + + +### Bubble +![alt text][bubble-image] + +From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. + +__Properties__ +* Stable +* Worst case performance O(n^2) +* Best case performance O(n) +* Average case performance O(n^2) + + +###### View the algorithm in [action][bubble-toptal] + + +### Caesar + + +### Insertion +![alt text][insertion-image] + +From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. + +__Properties__ +* Stable +* Worst case performance O(n^2) +* Best case performance O(n) +* Average case performance O(n^2) + + +###### View the algorithm in [action][insertion-toptal] + + + +[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort +[bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort +[bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort" + +[insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort +[insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort +[insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort" From b7eae6b0e37c0b44889657688a530f307c8cd2f5 Mon Sep 17 00:00:00 2001 From: Tony Sappe Date: Fri, 29 Jul 2016 15:14:30 -0400 Subject: [PATCH 6/9] Changed BubbleSort.py and InsertionSort.py to allow x number of inputs. Also worked on LinearSearch.py --- BubbleSort.py | 17 +++++++++-------- InsertionSort.py | 20 +++++++++++--------- LinearSearch.py | 43 +++++++++++++++++++++++-------------------- README.md | 1 + 4 files changed, 44 insertions(+), 37 deletions(-) diff --git a/BubbleSort.py b/BubbleSort.py index 513f788e0..0740c066b 100644 --- a/BubbleSort.py +++ b/BubbleSort.py @@ -12,13 +12,15 @@ def simple_bubble_sort(int_list): return int_list -def main(num): - inputs = [] - print("Enter any {} numbers for unsorted list: ".format(num)) +def main(): try: - for i in range(num): - n = input() - inputs.append(n) + print("Enter numbers separated by spaces:") + s = raw_input() + inputs = list(map(int, s.split(' '))) + if len(inputs) < 2: + print('No Enough values to sort!') + raise Exception + except Exception as e: print(e) else: @@ -27,5 +29,4 @@ def main(num): if __name__ == '__main__': print('==== Bubble Sort ====\n') - list_count = 6 - main(list_count) + main() diff --git a/InsertionSort.py b/InsertionSort.py index 679d06756..5602b2967 100644 --- a/InsertionSort.py +++ b/InsertionSort.py @@ -1,6 +1,7 @@ def simple_insertion_sort(int_list): - for i in range(1, 6): + count = len(int_list) + for i in range(1, count): temp = int_list[i] j = i - 1 while(j >= 0 and temp < int_list[j]): @@ -11,13 +12,15 @@ def simple_insertion_sort(int_list): return int_list -def main(num): - inputs = [] - print('Enter any {} numbers for unsorted list: '.format(num)) +def main(): try: - for i in range(num): - n = input() - inputs.append(n) + print("Enter numbers separated by spaces:") + s = raw_input() + inputs = list(map(int, s.split(' '))) + if len(inputs) < 2: + print('No Enough values to sort!') + raise Exception + except Exception as e: print(e) else: @@ -26,5 +29,4 @@ def main(num): if __name__ == '__main__': print('==== Insertion Sort ====\n') - list_count = 6 - main(list_count) + main() diff --git a/LinearSearch.py b/LinearSearch.py index 6180eac5a..cdff26b78 100644 --- a/LinearSearch.py +++ b/LinearSearch.py @@ -1,21 +1,24 @@ -def sequentialSearch(alist, item): - pos = 0 - found = False - - while pos < len(alist) and not found: - - if alist[pos] == item: - found = True - print("Found") - else: - pos = pos+1 - if found == False: - print("Not found") - return found - -print("Enter numbers seprated by space") -s = input() -numbers = list(map(int, s.split())) -trgt =int( input('enter a single number to be found in the list ')) -sequentialSearch(numbers, trgt) +def sequential_search(alist, target): + for index, item in enumerate(alist): + if item == target: + print("Found target {} at index {}".format(target, index)) + break + else: + print("Not found") + + +def main(): + try: + print("Enter numbers separated by spaces") + s = raw_input() + inputs = list(map(int, s.split(' '))) + target = int(raw_input('\nEnter a single number to be found in the list: ')) + except Exception as e: + print(e) + else: + sequential_search(inputs, target) + +if __name__ == '__main__': + print('==== Insertion Sort ====\n') + main() diff --git a/README.md b/README.md index de55ae89a..d88c5c675 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ ### **All Algorithms implemented in Python!** +These are for demonstration purposes only. There are many implementations of sorts in the Python standard library that are much better for performance reasons. ## Sorting From 37ddd2c8d06276141ce3b156c67e8663100a8dd0 Mon Sep 17 00:00:00 2001 From: Tony Sappe Date: Fri, 29 Jul 2016 15:31:20 -0400 Subject: [PATCH 7/9] Changed QuickSort.py Converted all indentations to spaces (different files had spaces or tabs) --- BubbleSort.py | 46 +++++++++++++++++++++++----------------------- InsertionSort.py | 46 +++++++++++++++++++++++----------------------- LinearSearch.py | 34 +++++++++++++++++----------------- QuickSort.py | 40 +++++++++++++++++++++------------------- README.md | 27 ++++++++++++++++++++------- 5 files changed, 104 insertions(+), 89 deletions(-) diff --git a/BubbleSort.py b/BubbleSort.py index 0740c066b..d74b5b223 100644 --- a/BubbleSort.py +++ b/BubbleSort.py @@ -1,32 +1,32 @@ def simple_bubble_sort(int_list): - count = len(int_list) - swapped = True - while (swapped): - swapped = False - for j in range(count - 1): - if (int_list[j] > int_list[j + 1]): - int_list[j], int_list[j + 1] = int_list[j + 1], int_list[j] - swapped = True - return int_list + count = len(int_list) + swapped = True + while (swapped): + swapped = False + for j in range(count - 1): + if (int_list[j] > int_list[j + 1]): + int_list[j], int_list[j + 1] = int_list[j + 1], int_list[j] + swapped = True + return int_list def main(): - try: - print("Enter numbers separated by spaces:") - s = raw_input() - inputs = list(map(int, s.split(' '))) - if len(inputs) < 2: - print('No Enough values to sort!') - raise Exception + try: + print("Enter numbers separated by spaces:") + s = raw_input() + inputs = list(map(int, s.split(' '))) + if len(inputs) < 2: + print('No Enough values to sort!') + raise Exception - except Exception as e: - print(e) - else: - sorted_input = simple_bubble_sort(inputs) - print('\nSorted list (min to max): {}'.format(sorted_input)) + except Exception as e: + print(e) + else: + sorted_input = simple_bubble_sort(inputs) + print('\nSorted list (min to max): {}'.format(sorted_input)) if __name__ == '__main__': - print('==== Bubble Sort ====\n') - main() + print('==== Bubble Sort ====\n') + main() diff --git a/InsertionSort.py b/InsertionSort.py index 5602b2967..74cbc57e8 100644 --- a/InsertionSort.py +++ b/InsertionSort.py @@ -1,32 +1,32 @@ def simple_insertion_sort(int_list): - count = len(int_list) - for i in range(1, count): - temp = int_list[i] - j = i - 1 - while(j >= 0 and temp < int_list[j]): - int_list[j + 1] = int_list[j] - j -= 1 - int_list[j + 1] = temp + count = len(int_list) + for i in range(1, count): + temp = int_list[i] + j = i - 1 + while(j >= 0 and temp < int_list[j]): + int_list[j + 1] = int_list[j] + j -= 1 + int_list[j + 1] = temp - return int_list + return int_list def main(): - try: - print("Enter numbers separated by spaces:") - s = raw_input() - inputs = list(map(int, s.split(' '))) - if len(inputs) < 2: - print('No Enough values to sort!') - raise Exception + try: + print("Enter numbers separated by spaces:") + s = raw_input() + inputs = list(map(int, s.split(' '))) + if len(inputs) < 2: + print('No Enough values to sort!') + raise Exception - except Exception as e: - print(e) - else: - sorted_input = simple_insertion_sort(inputs) - print('\nSorted list (min to max): {}'.format(sorted_input)) + except Exception as e: + print(e) + else: + sorted_input = simple_insertion_sort(inputs) + print('\nSorted list (min to max): {}'.format(sorted_input)) if __name__ == '__main__': - print('==== Insertion Sort ====\n') - main() + print('==== Insertion Sort ====\n') + main() diff --git a/LinearSearch.py b/LinearSearch.py index cdff26b78..61c9e0dd5 100644 --- a/LinearSearch.py +++ b/LinearSearch.py @@ -1,24 +1,24 @@ def sequential_search(alist, target): - for index, item in enumerate(alist): - if item == target: - print("Found target {} at index {}".format(target, index)) - break - else: - print("Not found") + for index, item in enumerate(alist): + if item == target: + print("Found target {} at index {}".format(target, index)) + break + else: + print("Not found") def main(): - try: - print("Enter numbers separated by spaces") - s = raw_input() - inputs = list(map(int, s.split(' '))) - target = int(raw_input('\nEnter a single number to be found in the list: ')) - except Exception as e: - print(e) - else: - sequential_search(inputs, target) + try: + print("Enter numbers separated by spaces") + s = raw_input() + inputs = list(map(int, s.split(' '))) + target = int(raw_input('\nEnter a single number to be found in the list: ')) + except Exception as e: + print(e) + else: + sequential_search(inputs, target) if __name__ == '__main__': - print('==== Insertion Sort ====\n') - main() + print('==== Linear Search ====\n') + main() diff --git a/QuickSort.py b/QuickSort.py index 89db5a6a3..7221cfe75 100644 --- a/QuickSort.py +++ b/QuickSort.py @@ -1,31 +1,33 @@ -def quicksort(A, p, r): +def quick_sort(A, p, r): if p < r: q = partition(A, p, r) - quicksort(A, p, q - 1) - quicksort(A, q + 1, r) + quick_sort(A, p, q - 1) + quick_sort(A, q + 1, r) + return A def partition(A, p, r): - x = A[r] i = p - 1 for j in range(p, r): - if A[j] <= x: + if A[j] <= A[r]: i += 1 - tmp = A[i] - A[i] = A[j] - A[j] = tmp - tmp = A[i+1] - A[i+1] = A[r] - A[r] = tmp + A[i], A[j] = A[j], A[i] + A[i + 1], A[r] = A[r], A[i + 1] return i + 1 -if __name__ == "__main__": - print('Enter values seperated by space:') - A = [int (item) for item in input().split(' ')] - # A = [23, 45, 43, 12, 67, 98, 123, 99] - # partition(A, 0, 7) - print(A) - quicksort(A, 0, 7) - print(A) +def main(): + try: + print("Enter numbers separated by spaces") + s = raw_input() + inputs = list(map(int, s.split(' '))) + except Exception as e: + print(e) + else: + sorted_input = quick_sort(inputs, 0, len(inputs) - 1) + print('\nSorted list (min to max): {}'.format(sorted_input)) + +if __name__ == '__main__': + print('==== Quick Sort ====\n') + main() diff --git a/README.md b/README.md index d88c5c675..b44e12e93 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,13 @@ # The Algoritms - Python -### **All Algorithms implemented in Python!** +### All Algorithms implemented in Python! These are for demonstration purposes only. There are many implementations of sorts in the Python standard library that are much better for performance reasons. -## Sorting - +## Sorting Algorithms ### Binary - +Add comments here ### Bubble ![alt text][bubble-image] @@ -16,7 +15,6 @@ These are for demonstration purposes only. There are many implementations of sor From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. __Properties__ -* Stable * Worst case performance O(n^2) * Best case performance O(n) * Average case performance O(n^2) @@ -26,7 +24,7 @@ __Properties__ ### Caesar - +Add comments here ### Insertion ![alt text][insertion-image] @@ -34,7 +32,6 @@ __Properties__ From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. __Properties__ -* Stable * Worst case performance O(n^2) * Best case performance O(n) * Average case performance O(n^2) @@ -43,6 +40,18 @@ __Properties__ ###### View the algorithm in [action][insertion-toptal] +## Quick +![alt text][quick-image] + +From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n log n) or O(n) with three-way partition +* Average case performance O(n^2) + + +###### View the algorithm in [action][quick-toptal] [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort [bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort @@ -51,3 +60,7 @@ __Properties__ [insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort [insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort [insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort" + +[quick-toptal]: https://www.toptal.com/developers/sorting-algorithms/quick-sort +[quick-wiki]: https://en.wikipedia.org/wiki/Quicksort +[quick-image]: https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif "Quick Sort" From 578845a6b5491c797ddad8eb61297e9f6383962c Mon Sep 17 00:00:00 2001 From: Tony Sappe Date: Fri, 29 Jul 2016 15:48:47 -0400 Subject: [PATCH 8/9] Improved MergeSort.py * Added Python3 support --- BubbleSort.py | 9 ++++- InsertionSort.py | 10 +++++- LinearSearch.py | 12 +++++-- MergeSort.py | 85 ++++++++++++++++++++++++++++++------------------ QuickSort.py | 10 +++++- README.md | 33 ++++++++++++++++--- 6 files changed, 118 insertions(+), 41 deletions(-) diff --git a/BubbleSort.py b/BubbleSort.py index d74b5b223..9f3579617 100644 --- a/BubbleSort.py +++ b/BubbleSort.py @@ -1,3 +1,4 @@ +import sys def simple_bubble_sort(int_list): @@ -13,9 +14,15 @@ def simple_bubble_sort(int_list): def main(): + # Python 2's `raw_input` has been renamed to `input` in Python 3 + if sys.version_info.major < 3: + input_function = raw_input + else: + input_function = input + try: print("Enter numbers separated by spaces:") - s = raw_input() + s = input_function() inputs = list(map(int, s.split(' '))) if len(inputs) < 2: print('No Enough values to sort!') diff --git a/InsertionSort.py b/InsertionSort.py index 74cbc57e8..a577c4a81 100644 --- a/InsertionSort.py +++ b/InsertionSort.py @@ -1,3 +1,5 @@ +import sys + def simple_insertion_sort(int_list): count = len(int_list) @@ -13,9 +15,15 @@ def simple_insertion_sort(int_list): def main(): + # Python 2's `raw_input` has been renamed to `input` in Python 3 + if sys.version_info.major < 3: + input_function = raw_input + else: + input_function = input + try: print("Enter numbers separated by spaces:") - s = raw_input() + s = input_function() inputs = list(map(int, s.split(' '))) if len(inputs) < 2: print('No Enough values to sort!') diff --git a/LinearSearch.py b/LinearSearch.py index 61c9e0dd5..82595eded 100644 --- a/LinearSearch.py +++ b/LinearSearch.py @@ -1,3 +1,5 @@ +import sys + def sequential_search(alist, target): for index, item in enumerate(alist): @@ -9,11 +11,17 @@ def sequential_search(alist, target): def main(): + # Python 2's `raw_input` has been renamed to `input` in Python 3 + if sys.version_info.major < 3: + input_function = raw_input + else: + input_function = input + try: print("Enter numbers separated by spaces") - s = raw_input() + s = input_function() inputs = list(map(int, s.split(' '))) - target = int(raw_input('\nEnter a single number to be found in the list: ')) + target = int(input_function('\nEnter a number to be found in list: ')) except Exception as e: print(e) else: diff --git a/MergeSort.py b/MergeSort.py index 7ce144dc7..ff3a31c70 100644 --- a/MergeSort.py +++ b/MergeSort.py @@ -1,36 +1,59 @@ -def mergeSort(alist): - print("Splitting ",alist) - if len(alist)>1: - mid = len(alist)//2 - lefthalf = alist[:mid] - righthalf = alist[mid:] - mergeSort(lefthalf) - mergeSort(righthalf) - i=0 - j=0 - k=0 - while i < len(lefthalf) and j < len(righthalf): - if lefthalf[i] < righthalf[j]: - alist[k]=lefthalf[i] - i=i+1 +import sys + + +def merge_sort(alist): + print("Splitting ", alist) + if len(alist) > 1: + mid = len(alist) // 2 + left_half = alist[:mid] + right_half = alist[mid:] + merge_sort(left_half) + merge_sort(right_half) + i = j = k = 0 + + while i < len(left_half) and j < len(right_half): + if left_half[i] < right_half[j]: + alist[k] = left_half[i] + i += 1 else: - alist[k]=righthalf[j] - j=j+1 - k=k+1 + alist[k] = right_half[j] + j += 1 + k += 1 - while i < len(lefthalf): - alist[k]=lefthalf[i] - i=i+1 - k=k+1 + while i < len(left_half): + alist[k] = left_half[i] + i += 1 + k += 1 - while j < len(righthalf): - alist[k]=righthalf[j] - j=j+1 - k=k+1 - print("Merging ",alist) + while j < len(right_half): + alist[k] = right_half[j] + j += 1 + k += 1 + print("Merging ", alist) + return alist -print("Enter numbers seprated by space") -s = input() -numbers = list(map(int, s.split())) -mergeSort(numbers) +def main(): + # Python 2's `raw_input` has been renamed to `input` in Python 3 + if sys.version_info.major < 3: + input_function = raw_input + else: + input_function = input + + try: + print("Enter numbers separated by spaces:") + s = input_function() + inputs = list(map(int, s.split(' '))) + if len(inputs) < 2: + print('No Enough values to sort!') + raise Exception + + except Exception as e: + print(e) + else: + sorted_input = merge_sort(inputs) + print('\nSorted list (min to max): {}'.format(sorted_input)) + +if __name__ == '__main__': + print('==== Merge Sort ====\n') + main() diff --git a/QuickSort.py b/QuickSort.py index 7221cfe75..2d922a3de 100644 --- a/QuickSort.py +++ b/QuickSort.py @@ -1,3 +1,5 @@ +import sys + def quick_sort(A, p, r): if p < r: @@ -18,9 +20,15 @@ def partition(A, p, r): def main(): + # Python 2's `raw_input` has been renamed to `input` in Python 3 + if sys.version_info.major < 3: + input_function = raw_input + else: + input_function = input + try: print("Enter numbers separated by spaces") - s = raw_input() + s = input_function() inputs = list(map(int, s.split(' '))) except Exception as e: print(e) diff --git a/README.md b/README.md index b44e12e93..65f0c70da 100644 --- a/README.md +++ b/README.md @@ -19,12 +19,9 @@ __Properties__ * Best case performance O(n) * Average case performance O(n^2) - ###### View the algorithm in [action][bubble-toptal] -### Caesar -Add comments here ### Insertion ![alt text][insertion-image] @@ -36,10 +33,22 @@ __Properties__ * Best case performance O(n) * Average case performance O(n^2) - ###### View the algorithm in [action][insertion-toptal] +## Merge +![alt text][merge-image] + +From [Wikipedia][merge-wiki]: In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945. + +__Properties__ +* Worst case performance O(n log n) +* Best case performance O(n) +* Average case performance O(n) + + +###### View the algorithm in [action][merge-toptal] + ## Quick ![alt text][quick-image] @@ -50,9 +59,19 @@ __Properties__ * Best case performance O(n log n) or O(n) with three-way partition * Average case performance O(n^2) - ###### View the algorithm in [action][quick-toptal] + +## Search Algorithms + +### Linear +Add comments here + +## Ciphers + +### Caesar +Add comments here + [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort [bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort [bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort" @@ -64,3 +83,7 @@ __Properties__ [quick-toptal]: https://www.toptal.com/developers/sorting-algorithms/quick-sort [quick-wiki]: https://en.wikipedia.org/wiki/Quicksort [quick-image]: https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif "Quick Sort" + +[merge-toptal]: https://www.toptal.com/developers/sorting-algorithms/merge-sort +[merge-wiki]: https://en.wikipedia.org/wiki/Merge_sort +[merge-image]: https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif "Merge Sort" From f9af3e8197bf564f6cc435b8981bae40fa88cf64 Mon Sep 17 00:00:00 2001 From: Tony Sappe Date: Fri, 29 Jul 2016 16:04:01 -0400 Subject: [PATCH 9/9] Typos in README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 65f0c70da..8fcf1a656 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# The Algoritms - Python +# The Algorithms - Python -### All Algorithms implemented in Python! +### All algorithms implemented in Python (for education) These are for demonstration purposes only. There are many implementations of sorts in the Python standard library that are much better for performance reasons.