diff --git a/searches/linear_search.py b/searches/linear_search.py index f42810092..24479e45b 100644 --- a/searches/linear_search.py +++ b/searches/linear_search.py @@ -13,7 +13,7 @@ from __future__ import print_function def linear_search(sequence, target): - """Pure implementation of binary search algorithm in Python + """Pure implementation of linear search algorithm in Python :param sequence: some sorted collection with comparable items :param target: item value to search diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py index 3bacb306f..2f14fd65f 100644 --- a/sorts/bubble_sort.py +++ b/sorts/bubble_sort.py @@ -30,7 +30,7 @@ def bubble_sort(collection): [-45, -5, -2] """ length = len(collection) - for i in range(length): + for i in range(length-1): for j in range(length-1): if collection[j] > collection[j+1]: collection[j], collection[j+1] = collection[j+1], collection[j] diff --git a/sorts/heap_sort.py b/sorts/heap_sort.py index 822bb6631..f89ae1866 100644 --- a/sorts/heap_sort.py +++ b/sorts/heap_sort.py @@ -7,7 +7,7 @@ or python3 -m doctest -v heap_sort.py For manual testing run: -python insertion_sort.py +python heap_sort.py ''' from __future__ import print_function @@ -46,7 +46,7 @@ def heap_sort(unsorted): n = len(unsorted) for i in range(n//2 - 1, -1, -1): heapify(unsorted, i, n) - for i in range(n - 1, -1, -1): + for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted diff --git a/sorts/insertion_sort.py b/sorts/insertion_sort.py index 646ed68ca..347c948df 100644 --- a/sorts/insertion_sort.py +++ b/sorts/insertion_sort.py @@ -29,14 +29,10 @@ def insertion_sort(collection): >>> insertion_sort([-2, -5, -45]) [-45, -5, -2] """ - length = len(collection) - for i in range(length): - current_item = collection[i] - j = i - 1 - while j >= 0 and current_item < collection[j]: - collection[j+1] = collection[j] - j -= 1 - collection[j+1] = current_item + for index in range(1, len(collection)): + while 0 < index and collection[index] < collection[index-1]: + collection[index], collection[index-1] = collection[index-1], collection[index] + index -= 1 return collection diff --git a/sorts/quick_sort.py b/sorts/quick_sort.py index f8e61ede4..257c21380 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -35,21 +35,20 @@ def quick_sort(collection): >>> quick_sort([-2, -5, -45]) [-45, -5, -2] """ + if len(collection) <= 1: + return collection less = [] equal = [] greater = [] - if len(collection) > 1: - pivot = collection[0] - for x in collection: - if x < pivot: - less.append(x) - if x == pivot: - equal.append(x) - if x > pivot: - greater.append(x) - return quick_sort(less) + equal + quick_sort(greater) - else: - return collection + pivot = collection[0] + for x in collection: + if x < pivot: + less.append(x) + elif x == pivot: + equal.append(x) + else: + greater.append(x) + return quick_sort(less) + equal + quick_sort(greater) if __name__ == '__main__':