Skip to content

Commit af520e8

Browse files
authored
Update bubble_sort.py
Added unoptimised version of iterative bubble sort implementation and comments
1 parent a71618f commit af520e8

1 file changed

Lines changed: 9 additions & 1 deletion

File tree

sorts/bubble_sort.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
from typing import Any
22

3+
def bubble_sort(collection: list[Any]) -> list[Any]:
4+
"""Non-optimised O(n^2) implementation of bubble sort algorithm (iterative)"""
5+
n = len(collection)
6+
for i in range(n):
7+
for j in range(n-1-i): # number of pairs
8+
if collection[j] > collection[j+1]:
9+
collection[j], collection[j+1] = collection[j+1], collection[j]
10+
return collection
311

412
def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
513
"""Pure implementation of bubble sort algorithm in Python
@@ -45,7 +53,7 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
4553
length = len(collection)
4654
for i in reversed(range(length)):
4755
swapped = False
48-
for j in range(i):
56+
for j in range(i): # number of pairs
4957
if collection[j] > collection[j + 1]:
5058
swapped = True
5159
collection[j], collection[j + 1] = collection[j + 1], collection[j]

0 commit comments

Comments
 (0)