Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I have changed some code in sorts/bubble_sort.py #11921

Closed
wants to merge 1 commit into from
Closed
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
135 changes: 26 additions & 109 deletions sorts/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,15 @@
from typing import Any
from typing import Any, List

Check failure on line 1 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

sorts/bubble_sort.py:1:1: UP035 `typing.List` is deprecated, use `list` instead

def bubble_sort_iterative(collection: List[Any]) -> List[Any]:

Check failure on line 3 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

sorts/bubble_sort.py:1:1: I001 Import block is un-sorted or un-formatted

Check failure on line 3 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/bubble_sort.py:3:39: UP006 Use `list` instead of `List` for type annotation

Check failure on line 3 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/bubble_sort.py:3:53: UP006 Use `list` instead of `List` for type annotation
"""Sorts a collection using the iterative bubble sort algorithm.

def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
"""Pure implementation of bubble sort algorithm in Python

:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending

Examples:
>>> bubble_sort_iterative([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort_iterative([])
[]
>>> bubble_sort_iterative([-2, -45, -5])
[-45, -5, -2]
>>> bubble_sort_iterative([-23, 0, 6, -4, 34])
[-23, -4, 0, 6, 34]
>>> bubble_sort_iterative([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
True
>>> bubble_sort_iterative([]) == sorted([])
True
>>> bubble_sort_iterative([-2, -45, -5]) == sorted([-2, -45, -5])
True
>>> bubble_sort_iterative([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
True
>>> bubble_sort_iterative(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
True
>>> bubble_sort_iterative(['z', 'a', 'y', 'b', 'x', 'c'])
['a', 'b', 'c', 'x', 'y', 'z']
>>> bubble_sort_iterative([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6])
[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
>>> bubble_sort_iterative([1, 3.3, 5, 7.7, 2, 4.4, 6])
[1, 2, 3.3, 4.4, 5, 6, 7.7]
>>> import random
>>> collection_arg = random.sample(range(-50, 50), 100)
>>> bubble_sort_iterative(collection_arg) == sorted(collection_arg)
True
>>> import string
>>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
>>> bubble_sort_iterative(collection_arg) == sorted(collection_arg)
True
:param collection: A mutable ordered collection with comparable items.
:return: The same collection ordered in ascending order.
"""
length = len(collection)
for i in reversed(range(length)):
for i in range(length):
swapped = False
for j in range(i):
for j in range(length - 1 - i):
if collection[j] > collection[j + 1]:
swapped = True
collection[j], collection[j + 1] = collection[j + 1], collection[j]
Expand All @@ -54,77 +18,30 @@
return collection


def bubble_sort_recursive(collection: list[Any]) -> list[Any]:
"""It is similar iterative bubble sort but recursive.

:param collection: mutable ordered sequence of elements
:return: the same list in ascending order
def bubble_sort_recursive(collection: List[Any]) -> List[Any]:

Check failure on line 21 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/bubble_sort.py:21:39: UP006 Use `list` instead of `List` for type annotation

Check failure on line 21 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/bubble_sort.py:21:53: UP006 Use `list` instead of `List` for type annotation
"""Sorts a collection using the recursive bubble sort algorithm.

Examples:
>>> bubble_sort_recursive([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort_iterative([])
[]
>>> bubble_sort_recursive([-2, -45, -5])
[-45, -5, -2]
>>> bubble_sort_recursive([-23, 0, 6, -4, 34])
[-23, -4, 0, 6, 34]
>>> bubble_sort_recursive([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
True
>>> bubble_sort_recursive([]) == sorted([])
True
>>> bubble_sort_recursive([-2, -45, -5]) == sorted([-2, -45, -5])
True
>>> bubble_sort_recursive([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
True
>>> bubble_sort_recursive(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
True
>>> bubble_sort_recursive(['z', 'a', 'y', 'b', 'x', 'c'])
['a', 'b', 'c', 'x', 'y', 'z']
>>> bubble_sort_recursive([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6])
[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
>>> bubble_sort_recursive([1, 3.3, 5, 7.7, 2, 4.4, 6])
[1, 2, 3.3, 4.4, 5, 6, 7.7]
>>> import random
>>> collection_arg = random.sample(range(-50, 50), 100)
>>> bubble_sort_recursive(collection_arg) == sorted(collection_arg)
True
>>> import string
>>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
>>> bubble_sort_recursive(collection_arg) == sorted(collection_arg)
True
:param collection: A mutable ordered sequence of elements.
:return: The same list in ascending order.
"""
length = len(collection)
if len(collection) <= 1:
return collection

Check failure on line 29 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/bubble_sort.py:29:1: W293 Blank line contains whitespace
# Perform a single pass of bubble sort
swapped = False
for i in range(length - 1):
for i in range(len(collection) - 1):
if collection[i] > collection[i + 1]:
collection[i], collection[i + 1] = collection[i + 1], collection[i]
swapped = True

return collection if not swapped else bubble_sort_recursive(collection)
collection[i], collection[i + 1] = collection[i + 1], collection[i]

Check failure on line 36 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/bubble_sort.py:36:1: W293 Blank line contains whitespace
if not swapped:
return collection

Check failure on line 39 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/bubble_sort.py:39:1: W293 Blank line contains whitespace
return bubble_sort_recursive(collection[:-1]) + [collection[-1]]

Check failure on line 40 in sorts/bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (RUF005)

sorts/bubble_sort.py:40:12: RUF005 Consider iterable unpacking instead of concatenation


if __name__ == "__main__":
import doctest
from random import sample
from timeit import timeit

doctest.testmod()

# Benchmark: Iterative seems slightly faster than recursive.
num_runs = 10_000
unsorted = sample(range(-50, 50), 100)
timer_iterative = timeit(
"bubble_sort_iterative(unsorted[:])", globals=globals(), number=num_runs
)
print("\nIterative bubble sort:")
print(*bubble_sort_iterative(unsorted), sep=",")
print(f"Processing time (iterative): {timer_iterative:.5f}s for {num_runs:,} runs")

unsorted = sample(range(-50, 50), 100)
timer_recursive = timeit(
"bubble_sort_recursive(unsorted[:])", globals=globals(), number=num_runs
)
print("\nRecursive bubble sort:")
print(*bubble_sort_recursive(unsorted), sep=",")
print(f"Processing time (recursive): {timer_recursive:.5f}s for {num_runs:,} runs")
# Example usage
sample_list = [5, 3, 8, 6, 2]
print("Iterative Bubble Sort:", bubble_sort_iterative(sample_list.copy()))
print("Recursive Bubble Sort:", bubble_sort_recursive(sample_list.copy()))