|
2 | 2 |
|
3 | 3 |
|
4 | 4 | def bubble_sort_iterative(collection: list[Any]) -> list[Any]: |
5 | | - """Pure implementation of bubble sort algorithm in Python |
| 5 | + """Pure implementation of the bubble sort algorithm in Python (iterative). |
| 6 | +
|
| 7 | + Bubble sort works by repeatedly stepping through the collection, |
| 8 | + comparing each pair of adjacent elements and swapping them if they |
| 9 | + are in the wrong order. This process repeats, with each full pass |
| 10 | + "bubbling" the next-largest unsorted element into its correct |
| 11 | + position at the end of the collection, until a full pass completes |
| 12 | + with no swaps, at which point the collection is sorted. |
| 13 | +
|
| 14 | + Time complexity: O(n) best case (already sorted, thanks to the |
| 15 | + early-exit optimization), O(n^2) average and worst case. |
| 16 | + Space complexity: O(1) auxiliary (sorts in place). |
6 | 17 |
|
7 | 18 | :param collection: some mutable ordered collection with heterogeneous |
8 | 19 | comparable items inside |
@@ -61,7 +72,19 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]: |
61 | 72 |
|
62 | 73 |
|
63 | 74 | def bubble_sort_recursive(collection: list[Any]) -> list[Any]: |
64 | | - """It is similar iterative bubble sort but recursive. |
| 75 | + """Pure implementation of the bubble sort algorithm in Python (recursive). |
| 76 | +
|
| 77 | + Functionally identical to the iterative version: each call makes a |
| 78 | + single pass through the collection, comparing adjacent elements and |
| 79 | + swapping any pair that is out of order. If any swap occurred during |
| 80 | + the pass, the function calls itself again on the (partially sorted) |
| 81 | + collection; once a pass completes with no swaps, the collection is |
| 82 | + sorted and the recursion stops. |
| 83 | +
|
| 84 | + Time complexity: O(n) best case (already sorted), O(n^2) average and |
| 85 | + worst case. |
| 86 | + Space complexity: O(1) auxiliary for the sort itself (sorts in place), |
| 87 | + though the recursion adds O(n) call-stack frames in the worst case. |
65 | 88 |
|
66 | 89 | :param collection: mutable ordered sequence of elements |
67 | 90 | :return: the same list in ascending order |
|
0 commit comments