From 5377d01be070aa15b0ff6c86ecd27a15c5f51fce Mon Sep 17 00:00:00 2001 From: Ali Satwat Khan Date: Sun, 12 Jul 2026 17:09:26 +0500 Subject: [PATCH] docs: expand bubble sort docstrings with algorithm explanation Add a concise description of how bubble sort works (repeated adjacent comparisons/swaps until a pass makes no swaps) and note time/space complexity for both the iterative and recursive implementations. No behavior changes; all existing doctests pass. --- sorts/bubble_sort.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py index 4d658a4a12e4..c66d5d59dd93 100644 --- a/sorts/bubble_sort.py +++ b/sorts/bubble_sort.py @@ -2,7 +2,18 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]: - """Pure implementation of bubble sort algorithm in Python + """Pure implementation of the bubble sort algorithm in Python (iterative). + + Bubble sort works by repeatedly stepping through the collection, + comparing each pair of adjacent elements and swapping them if they + are in the wrong order. This process repeats, with each full pass + "bubbling" the next-largest unsorted element into its correct + position at the end of the collection, until a full pass completes + with no swaps, at which point the collection is sorted. + + Time complexity: O(n) best case (already sorted, thanks to the + early-exit optimization), O(n^2) average and worst case. + Space complexity: O(1) auxiliary (sorts in place). :param collection: some mutable ordered collection with heterogeneous comparable items inside @@ -61,7 +72,19 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]: def bubble_sort_recursive(collection: list[Any]) -> list[Any]: - """It is similar iterative bubble sort but recursive. + """Pure implementation of the bubble sort algorithm in Python (recursive). + + Functionally identical to the iterative version: each call makes a + single pass through the collection, comparing adjacent elements and + swapping any pair that is out of order. If any swap occurred during + the pass, the function calls itself again on the (partially sorted) + collection; once a pass completes with no swaps, the collection is + sorted and the recursion stops. + + Time complexity: O(n) best case (already sorted), O(n^2) average and + worst case. + Space complexity: O(1) auxiliary for the sort itself (sorts in place), + though the recursion adds O(n) call-stack frames in the worst case. :param collection: mutable ordered sequence of elements :return: the same list in ascending order