|
1 | 1 | """
|
2 |
| -This is a pure Python implementation of the quick sort algorithm |
| 2 | +A pure Python implementation of the quick sort algorithm |
3 | 3 |
|
4 | 4 | For doctests run following command:
|
5 |
| -python -m doctest -v quick_sort.py |
6 |
| -or |
7 | 5 | python3 -m doctest -v quick_sort.py
|
8 | 6 |
|
9 | 7 | For manual testing run:
|
10 |
| -python quick_sort.py |
| 8 | +python3 quick_sort.py |
11 | 9 | """
|
12 | 10 |
|
13 | 11 |
|
14 |
| -def quick_sort(collection): |
15 |
| - """Pure implementation of quick sort algorithm in Python |
| 12 | +def quick_sort(collection: list) -> list: |
| 13 | + """A pure Python implementation of quick sort algorithm |
16 | 14 |
|
17 |
| - :param collection: some mutable ordered collection with heterogeneous |
18 |
| - comparable items inside |
| 15 | + :param collection: a mutable collection of comparable items |
19 | 16 | :return: the same collection ordered by ascending
|
20 | 17 |
|
21 | 18 | Examples:
|
22 | 19 | >>> quick_sort([0, 5, 3, 2, 2])
|
23 | 20 | [0, 2, 2, 3, 5]
|
24 |
| -
|
25 | 21 | >>> quick_sort([])
|
26 | 22 | []
|
27 |
| -
|
28 |
| - >>> quick_sort([-2, -5, -45]) |
29 |
| - [-45, -5, -2] |
| 23 | + >>> quick_sort([-2, 5, 0, -45]) |
| 24 | + [-45, -2, 0, 5] |
30 | 25 | """
|
31 |
| - length = len(collection) |
32 |
| - if length <= 1: |
| 26 | + if len(collection) < 2: |
33 | 27 | return collection
|
34 |
| - else: |
35 |
| - # Use the last element as the first pivot |
36 |
| - pivot = collection.pop() |
37 |
| - # Put elements greater than pivot in greater list |
38 |
| - # Put elements lesser than pivot in lesser list |
39 |
| - greater, lesser = [], [] |
40 |
| - for element in collection: |
41 |
| - if element > pivot: |
42 |
| - greater.append(element) |
43 |
| - else: |
44 |
| - lesser.append(element) |
45 |
| - return quick_sort(lesser) + [pivot] + quick_sort(greater) |
| 28 | + pivot = collection.pop() # Use the last element as the first pivot |
| 29 | + greater = [] # All elements greater than pivot |
| 30 | + lesser = [] # All elements less than or equal to pivot |
| 31 | + for element in collection: |
| 32 | + (greater if element > pivot else lesser).append(element) |
| 33 | + return quick_sort(lesser) + [pivot] + quick_sort(greater) |
46 | 34 |
|
47 | 35 |
|
48 | 36 | if __name__ == "__main__":
|
|
0 commit comments