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
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> bubble_sort([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
True
>>> bubble_sort([]) == sorted([])
True
>>> bubble_sort([-2, -45, -5]) == sorted([-2, -45, -5])
True
>>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
True
>>> bubble_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c'])
True
>>> import random
>>> collection = random.sample(range(-50, 50), 100)
>>> bubble_sort(collection) == sorted(collection)
True
>>> import string
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
>>> bubble_sort(collection) == sorted(collection)
True
"""
length = len(collection)
for i in reversed(range(length)):
swapped = False
for j in range(i):
if collection[j] > collection[j + 1]:
swapped = True
collection[j], collection[j + 1] = collection[j + 1], collection[j]
if not swapped:
break # Stop iteration if the collection is sorted.
return collection
if __name__ == "__main__":
import doctest
import time
doctest.testmod()
user_input = input("Enter numbers separated by a comma:").strip()
unsorted = [int(item) for item in user_input.split(",")]
start = time.process_time()
print(*bubble_sort(unsorted), sep=",")
print(f"Processing time: {(time.process_time() - start)%1e9 + 7}")
Given an unsorted array of n elements, write a function to sort the array
O(n^2)
Worst case performance
O(n)
Best-case performance
O(n^2)
Average performance
O(1)
Worst case
arr[] = {10, 80, 40, 30}
Indexes: 0 1 2 3
1. Index = 0, Number = 10
2. 10 < 80, do nothing and continue
3. Index = 1, Number = 80
4. 80 > 40, swap 80 and 40
5. The array now is {10, 40, 80, 30}
6. Index = 2, Number = 80
7. 80 > 30, swap 80 and 30
8. The array now is {10, 40, 30, 80}
Repeat the Above Steps again
arr[] = {10, 40, 30, 80}
Indexes: 0 1 2 3
1. Index = 0, Number = 10
2. 10 < 40, do nothing and continue
3. Index = 1, Number = 40
4. 40 > 30, swap 40 and 30
5. The array now is {10, 30, 40, 80}
6. Index = 2, Number = 40
7. 40 < 80, do nothing
8. The array now is {10, 30, 40, 80}
Repeat the Above Steps again
arr[] = {10, 30, 40, 80}
Indexes: 0 1 2 3
1. Index = 0, Number = 10
2. 10 < 30, do nothing and continue
3. Index = 1, Number = 30
4. 30 < 40, do nothing and continue
5. Index = 2, Number = 40
6. 40 < 80, do nothing
Since there are no swaps in above steps, it means the array is sorted and we can stop here.
A video explaining the Bubble Sort Algorithm
Bubble sort is also known as Sinking sort.