|
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 bubble sort algorithm in Python. |
| 6 | +
|
| 7 | + Repeatedly steps through the list, compares adjacent elements, and swaps |
| 8 | + them if they are in the wrong order. The pass through the list is repeated |
| 9 | + until the list is sorted. Stops early if no swaps are made in a pass. |
6 | 10 |
|
7 | 11 | :param collection: some mutable ordered collection with heterogeneous |
8 | 12 | comparable items inside |
9 | 13 | :return: the same collection ordered in ascending order |
10 | 14 |
|
| 15 | + Time Complexity: |
| 16 | + Best Case: O(n) — already sorted (early exit via swapped flag) |
| 17 | + Average Case: O(n²) |
| 18 | + Worst Case: O(n²) |
| 19 | + Space Complexity: O(1) — in-place sorting |
| 20 | + Stable: Yes |
| 21 | +
|
11 | 22 | Examples: |
12 | 23 | >>> bubble_sort_iterative([0, 5, 2, 3, 2]) |
13 | 24 | [0, 2, 2, 3, 5] |
@@ -61,11 +72,21 @@ 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 recursive implementation of bubble sort algorithm in Python. |
| 76 | +
|
| 77 | + Performs one pass to bubble the largest unsorted element to the end, |
| 78 | + then recursively sorts the remaining elements. Stops when no swaps occur. |
65 | 79 |
|
66 | 80 | :param collection: mutable ordered sequence of elements |
67 | 81 | :return: the same list in ascending order |
68 | 82 |
|
| 83 | + Time Complexity: |
| 84 | + Best Case: O(n²) — recursive call stack prevents early exit |
| 85 | + Average Case: O(n²) |
| 86 | + Worst Case: O(n²) |
| 87 | + Space Complexity: O(n) — recursive call stack depth |
| 88 | + Stable: Yes |
| 89 | +
|
69 | 90 | Examples: |
70 | 91 | >>> bubble_sort_recursive([0, 5, 2, 3, 2]) |
71 | 92 | [0, 2, 2, 3, 5] |
|
0 commit comments