A pure Python implementation of quicksort algorithm. :param collection: a mutable collection of comparable items :return: the same collection ordered in ascending order Examples: >>> quick_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> quick_sort([]) [] >>> quick_sort([-
(collection: list)
| 14 | |
| 15 | |
| 16 | def quick_sort(collection: list) -> list: |
| 17 | """A pure Python implementation of quicksort algorithm. |
| 18 | |
| 19 | :param collection: a mutable collection of comparable items |
| 20 | :return: the same collection ordered in ascending order |
| 21 | |
| 22 | Examples: |
| 23 | >>> quick_sort([0, 5, 3, 2, 2]) |
| 24 | [0, 2, 2, 3, 5] |
| 25 | >>> quick_sort([]) |
| 26 | [] |
| 27 | >>> quick_sort([-2, 5, 0, -45]) |
| 28 | [-45, -2, 0, 5] |
| 29 | """ |
| 30 | # Base case: if the collection has 0 or 1 elements, it is already sorted |
| 31 | if len(collection) < 2: |
| 32 | return collection |
| 33 | |
| 34 | # Randomly select a pivot index and remove the pivot element from the collection |
| 35 | pivot_index = randrange(len(collection)) |
| 36 | pivot = collection.pop(pivot_index) |
| 37 | |
| 38 | # Partition the remaining elements into two groups: lesser or equal, and greater |
| 39 | lesser = [item for item in collection if item <= pivot] |
| 40 | greater = [item for item in collection if item > pivot] |
| 41 | |
| 42 | # Recursively sort the lesser and greater groups, and combine with the pivot |
| 43 | return [*quick_sort(lesser), pivot, *quick_sort(greater)] |
| 44 | |
| 45 | |
| 46 | if __name__ == "__main__": |