-
-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Expand file tree
/
Copy pathbubble_sort.py
More file actions
69 lines (50 loc) · 1.55 KB
/
bubble_sort.py
File metadata and controls
69 lines (50 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from typing import Any
"""
Bubble Sort Algorithms
This module provides iterative and optimized implementations
of the Bubble Sort algorithm.
Time Complexity:
Best Case: O(n)
Average Case: O(n^2)
Worst Case: O(n^2)
Space Complexity:
O(1)
"""
def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
"""
Bubble Sort (Iterative)
Sorts a list in ascending order using the bubble sort algorithm.
:param collection: A mutable list of comparable elements
:return: Sorted list
"""
n = len(collection)
if n < 2:
return collection
for i in range(n):
swapped = False
for j in range(n - i - 1): # removed unnecessary start=0
if collection[j] > collection[j + 1]:
collection[j], collection[j + 1] = collection[j + 1], collection[j]
swapped = True
if not swapped:
break
return collection
def bubble_sort_optimized(collection: list[Any]) -> list[Any]:
"""
Optimized Bubble Sort
Uses the last swap position to reduce unnecessary comparisons
when part of the list is already sorted.
:param collection: A mutable list of comparable elements
:return: Sorted list
"""
n = len(collection)
if n < 2:
return collection
while n > 1:
last_swap = 0
for i in range(1, n):
if collection[i - 1] > collection[i]:
collection[i - 1], collection[i] = collection[i], collection[i - 1]
last_swap = i
n = last_swap
return collection