Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions sorts/bubble_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down