Skip to content
Merged
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
9 changes: 6 additions & 3 deletions sorts/bubble_sort.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
def bubble_sort(collection):
from typing import Any


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

:param collection: some mutable ordered collection with heterogeneous
Expand DownExpand Up@@ -28,9 +31,9 @@ def bubble_sort(collection):
True
"""
length = len(collection)
for i in range(length - 1):
for i in reversed(range(length)):

@l3str4ngel3str4ngeNov 10, 2021

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is calling reversed more efficient? I don't think so. Did you do some benchmarks?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reversed has to be a bit better since the Python heapq.py module uses it.
It also improves code readability. @l3str4nge

Source: https://www.python.org/dev/peps/pep-0322/

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know but it would be good to know if algorithms performance is better too :) Could you perform any benchmarks before and after refactor?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benchmarked with the timeit module:

1000 items:

Before: 0.10902250000071945
After: 0.11019620000297436

5000 items:

Before: 2.8898907999973744
After: 2.844012000001385

10000 items:

Before: 12.34897049999563
After: 11.655540399995516

I tested a bit more locally and sometimes refactored one is better and sometimes it's the original.

swapped = False
for j in range(length - 1 - i):
for j in range(i):
if collection[j] > collection[j + 1]:
swapped = True
collection[j], collection[j + 1] = collection[j + 1], collection[j]
Expand Down