diff options
Diffstat (limited to 'algorithms/impl')
-rw-r--r-- | algorithms/impl/__init__.py | 30 | ||||
-rw-r--r-- | algorithms/impl/bubble_sort.py | 56 | ||||
-rw-r--r-- | algorithms/impl/heapsort.py | 82 | ||||
-rw-r--r-- | algorithms/impl/insertion_sort.py | 37 | ||||
-rw-r--r-- | algorithms/impl/median.py | 67 | ||||
-rw-r--r-- | algorithms/impl/merge_sort.py | 52 | ||||
-rw-r--r-- | algorithms/impl/quicksort.py | 103 | ||||
-rw-r--r-- | algorithms/impl/selection_sort.py | 39 |
8 files changed, 466 insertions, 0 deletions
diff --git a/algorithms/impl/__init__.py b/algorithms/impl/__init__.py new file mode 100644 index 0000000..84bd702 --- /dev/null +++ b/algorithms/impl/__init__.py @@ -0,0 +1,30 @@ +# Copyright (c) 2016 Egor Tensin <Egor.Tensin@gmail.com> +# This file is part of the "Sorting algorithms" project. +# For details, see https://github.com/egor-tensin/sorting-algorithms. +# Distributed under the MIT License. + +from importlib import import_module +import os.path +from pkgutil import iter_modules + +from .. import algorithm + + +_ALGORITHMS_NAME = '_ALGORITHMS' + + +def refresh_algorithms(): + all_algorithms = {} + + for _, module_name, is_pkg in iter_modules([os.path.dirname(__file__)]): + if is_pkg: + continue + module = import_module('.' + module_name, __package__) + if hasattr(module, _ALGORITHMS_NAME): + module_algorithms = getattr(module, _ALGORITHMS_NAME) + for descr in module_algorithms: + assert isinstance(descr, algorithm.Algorithm) + assert descr.codename not in all_algorithms + all_algorithms[descr.codename] = descr + + return all_algorithms diff --git a/algorithms/impl/bubble_sort.py b/algorithms/impl/bubble_sort.py new file mode 100644 index 0000000..0ea66bb --- /dev/null +++ b/algorithms/impl/bubble_sort.py @@ -0,0 +1,56 @@ +# Copyright (c) 2015 Egor Tensin <Egor.Tensin@gmail.com> +# This file is part of the "Sorting algorithms" project. +# For details, see https://github.com/egor-tensin/sorting-algorithms. +# Distributed under the MIT License. + +import sys + +from ..algorithm import SortingAlgorithm + + +def bubble_sort(xs): + while True: + swapped = False + for i in range(1, len(xs)): + if xs[i - 1] > xs[i]: + xs[i], xs[i - 1] = xs[i - 1], xs[i] + swapped = True + if not swapped: + break + return xs + + +def bubble_sort_optimized(xs): + n = len(xs) + while True: + new_n = 0 + for i in range(1, n): + if xs[i - 1] > xs[i]: + xs[i], xs[i - 1] = xs[i - 1], xs[i] + new_n = i + n = new_n + if not n: + break + return xs + + +_ALGORITHMS = [ + SortingAlgorithm('bubble_sort', 'Bubble sort', bubble_sort), + SortingAlgorithm('bubble_sort_optimized', 'Bubble sort (optimized)', bubble_sort_optimized), +] + + +def _parse_args(args=None): + if args is None: + args = sys.argv[1:] + return list(map(int, args)) + + +def main(args=None): + xs = _parse_args(args) + print(bubble_sort(list(xs))) + print(bubble_sort_optimized(list(xs))) + + +if __name__ == '__main__': + main() diff --git a/algorithms/impl/heapsort.py b/algorithms/impl/heapsort.py new file mode 100644 index 0000000..81bea20 --- /dev/null +++ b/algorithms/impl/heapsort.py @@ -0,0 +1,82 @@ +# Copyright (c) 2015 Egor Tensin <Egor.Tensin@gmail.com> +# This file is part of the "Sorting algorithms" project. +# For details, see https://github.com/egor-tensin/sorting-algorithms. +# Distributed under the MIT License. + +import sys + +from ..algorithm import SortingAlgorithm + +# Disclaimer: implemented in the most literate way. + + +def heapsort(xs): + _heapify(xs) + first, last = 0, len(xs) - 1 + for end in range(last, first, -1): + xs[end], xs[first] = xs[first], xs[end] + _siftdown(xs, first, end - 1) + return xs + + +# In a heap stored in a zero-based array, +# left_child = node * 2 + 1 +# right_child = node * 2 + 2 +# parent = (node - 1) // 2 + + +def _get_parent(node): + return (node - 1) // 2 + + +def _get_left_child(node): + return node * 2 + 1 + + +def _get_right_child(node): + return node * 2 + 2 + + +def _heapify(xs): + last = len(xs) - 1 + first_parent, last_parent = 0, _get_parent(last) + for parent in range(last_parent, first_parent - 1, -1): + _siftdown(xs, parent, last) + + +def _siftdown(xs, start, end): + root = start + while True: + # We swap if there is at least one child + child = _get_left_child(root) + if child > end: + break + # If there are two children, select the minimum + right_child = _get_right_child(root) + if right_child <= end and xs[child] < xs[right_child]: + child = right_child + if xs[root] < xs[child]: + xs[root], xs[child] = xs[child], xs[root] + root = child + else: + break + + +_ALGORITHMS = [ + SortingAlgorithm('heapsort', 'Heapsort', heapsort), +] + + +def _parse_args(args=None): + if args is None: + args = sys.argv[1:] + return list(map(int, args)) + + +def main(args=None): + xs = _parse_args(args) + print(heapsort(list(xs))) + + +if __name__ == '__main__': + main() diff --git a/algorithms/impl/insertion_sort.py b/algorithms/impl/insertion_sort.py new file mode 100644 index 0000000..13f16a0 --- /dev/null +++ b/algorithms/impl/insertion_sort.py @@ -0,0 +1,37 @@ +# Copyright (c) 2015 Egor Tensin <Egor.Tensin@gmail.com> +# This file is part of the "Sorting algorithms" project. +# For details, see https://github.com/egor-tensin/sorting-algorithms. +# Distributed under the MIT License. + +import sys + +from ..algorithm import SortingAlgorithm + + +def insertion_sort(xs): + for i in range(1, len(xs)): + j = i + while j > 0 and xs[j - 1] > xs[j]: + xs[j], xs[j - 1] = xs[j - 1], xs[j] + j -= 1 + return xs + + +_ALGORITHMS = [ + SortingAlgorithm('insertion_sort', 'Insertion sort', insertion_sort), +] + + +def _parse_args(args=None): + if args is None: + args = sys.argv[1:] + return list(map(int, args)) + + +def main(args=None): + xs = _parse_args(args) + print(insertion_sort(list(xs))) + + +if __name__ == '__main__': + main() diff --git a/algorithms/impl/median.py b/algorithms/impl/median.py new file mode 100644 index 0000000..a754cdb --- /dev/null +++ b/algorithms/impl/median.py @@ -0,0 +1,67 @@ +# Copyright (c) 2016 Egor Tensin <Egor.Tensin@gmail.com> +# This file is part of the "Sorting algorithms" project. +# For details, see https://github.com/egor-tensin/sorting-algorithms. +# Distributed under the MIT License. + +from heapq import heappush, heappop +import sys + +from ..algorithm import Algorithm +from .quicksort import quicksort_random + + +def calc_median_heaps(xs): + cur_median = 0.0 + min_heap, max_heap = [], [] + for x in xs: + if x < cur_median: + heappush(max_heap, -x) + elif x > cur_median or len(max_heap) > len(min_heap): + heappush(min_heap, x) + else: + heappush(max_heap, -x) + + if len(max_heap) > len(min_heap) + 1: + heappush(min_heap, -heappop(max_heap)) + elif len(min_heap) > len(max_heap) + 1: + heappush(max_heap, -heappop(min_heap)) + + if len(max_heap) > len(min_heap): + cur_median = -max_heap[0] + elif len(max_heap) == len(min_heap): + cur_median = -max_heap[0] / 2 + min_heap[0] / 2 + else: + cur_median = min_heap[0] + return cur_median + + +def calc_median_sorting(xs): + if not xs: + return 0.0 + quicksort_random(xs) + if len(xs) % 2: + return xs[len(xs) // 2] + else: + return xs[len(xs) // 2 - 1] / 2 + xs[len(xs) // 2] / 2 + + +_ALGORITHMS = [ + Algorithm('median_sorting', 'Median value (using explicit sorting)', calc_median_sorting), + Algorithm('median_heaps', 'Median value (using heaps)', calc_median_heaps), +] + + +def _parse_args(args=None): + if args is None: + args = sys.argv[1:] + return list(map(int, args)) + + +def main(args=None): + xs = _parse_args(args) + print(calc_median_sorting(list(xs))) + print(calc_median_heaps(list(xs))) + + +if __name__ == '__main__': + main() diff --git a/algorithms/impl/merge_sort.py b/algorithms/impl/merge_sort.py new file mode 100644 index 0000000..fecdf78 --- /dev/null +++ b/algorithms/impl/merge_sort.py @@ -0,0 +1,52 @@ +# Copyright (c) 2015 Egor Tensin <Egor.Tensin@gmail.com> +# This file is part of the "Sorting algorithms" project. +# For details, see https://github.com/egor-tensin/sorting-algorithms. +# Distributed under the MIT License. + +import sys + +from ..algorithm import SortingAlgorithm + + +def merge(left, right): + result = [] + l, r = 0, 0 + while l < len(left) and r < len(right): + if left[l] <= right[r]: + result.append(left[l]) + l += 1 + else: + result.append(right[r]) + r += 1 + if left: + result.extend(left[l:]) + if right: + result.extend(right[r:]) + return result + + +def merge_sort(xs): + if len(xs) < 2: + return xs + mid = len(xs) // 2 + return merge(merge_sort(xs[:mid]), merge_sort(xs[mid:])) + + +_ALGORITHMS = [ + SortingAlgorithm('merge_sort', 'Merge sort', merge_sort), +] + + +def _parse_args(args=None): + if args is None: + args = sys.argv[1:] + return list(map(int, args)) + + +def main(args=None): + xs = _parse_args(args) + print(merge_sort(list(xs))) + + +if __name__ == '__main__': + main() diff --git a/algorithms/impl/quicksort.py b/algorithms/impl/quicksort.py new file mode 100644 index 0000000..dd0c92b --- /dev/null +++ b/algorithms/impl/quicksort.py @@ -0,0 +1,103 @@ +# Copyright (c) 2015 Egor Tensin <Egor.Tensin@gmail.com> +# This file is part of the "Sorting algorithms" project. +# For details, see https://github.com/egor-tensin/sorting-algorithms. +# Distributed under the MIT License. + +from random import randrange, seed +import sys + +from ..algorithm import SortingAlgorithm + + +seed() + + +def _partition(xs, beg, end, select_pivot): + pivot = select_pivot(xs, beg, end) + xs[pivot], xs[end] = xs[end], xs[pivot] + for i in range(beg, end): + if xs[i] <= xs[end]: + xs[i], xs[beg] = xs[beg], xs[i] + beg += 1 + xs[beg], xs[end] = xs[end], xs[beg] + return beg + + +def _quicksort(xs, beg, end, select_pivot): + if beg < end: + pivot = _partition(xs, beg, end, select_pivot) + _quicksort(xs, beg, pivot - 1, select_pivot) + _quicksort(xs, pivot + 1, end, select_pivot) + + +def _select_first(xs, beg, end): + return beg + + +def _select_second(xs, beg, end): + return beg + 1 + + +def _select_middle(xs, beg, end): + return (beg + end) // 2 + + +def _select_last(xs, beg, end): + return end + + +def _select_random(xs, beg, end): + return randrange(beg, end + 1) + + +def quicksort_first(xs): + _quicksort(xs, 0, len(xs) - 1, _select_first) + return xs + + +def quicksort_second(xs): + _quicksort(xs, 0, len(xs) - 1, _select_second) + return xs + + +def quicksort_middle(xs): + _quicksort(xs, 0, len(xs) - 1, _select_middle) + return xs + + +def quicksort_last(xs): + _quicksort(xs, 0, len(xs) - 1, _select_last) + return xs + + +def quicksort_random(xs): + _quicksort(xs, 0, len(xs) - 1, _select_random) + return xs + + +_ALGORITHMS = [ + SortingAlgorithm('quicksort_first', 'Quicksort (first element as pivot)', quicksort_first), + SortingAlgorithm('quicksort_second', 'Quicksort (second element as pivot)', quicksort_second), + SortingAlgorithm('quicksort_middle', 'Quicksort (middle element as pivot)', quicksort_middle), + SortingAlgorithm('quicksort_last', 'Quicksort (last element as pivot)', quicksort_last), + SortingAlgorithm('quicksort_random', 'Quicksort (random element as pivot)', quicksort_random), +] + + +def _parse_args(args=None): + if args is None: + args = sys.argv[1:] + return list(map(int, args)) + + +def main(args=None): + xs = _parse_args(args) + print(quicksort_first(list(xs))) + print(quicksort_second(list(xs))) + print(quicksort_middle(list(xs))) + print(quicksort_last(list(xs))) + print(quicksort_random(list(xs))) + + +if __name__ == '__main__': + main() diff --git a/algorithms/impl/selection_sort.py b/algorithms/impl/selection_sort.py new file mode 100644 index 0000000..e9a5a09 --- /dev/null +++ b/algorithms/impl/selection_sort.py @@ -0,0 +1,39 @@ +# Copyright (c) 2015 Egor Tensin <Egor.Tensin@gmail.com> +# This file is part of the "Sorting algorithms" project. +# For details, see https://github.com/egor-tensin/sorting-algorithms. +# Distributed under the MIT License. + +import sys + +from ..algorithm import SortingAlgorithm + + +def selection_sort(xs): + for i in range(len(xs) - 1): + min_i = i + for j in range(i + 1, len(xs)): + if xs[j] < xs[min_i]: + min_i = j + if min_i != i: + xs[i], xs[min_i] = xs[min_i], xs[i] + return xs + + +_ALGORITHMS = [ + SortingAlgorithm('selection_sort', 'Selection sort', selection_sort), +] + + +def _parse_args(args=None): + if args is None: + args = sys.argv[1:] + return list(map(int, args)) + + +def main(args=None): + xs = _parse_args(args) + print(selection_sort(list(xs))) + + +if __name__ == '__main__': + main() |