Bubble Sort
def bubble_sort(arr):
n = len(arr)
# walk through array for len() times
for i in range(n):
# each time the biggest one will swap to the end of the list
# only 'n-i' times afterward needed
for j in range(0, n - i - 1):
# compare and swap
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if __name__ == "__main__":
import random
arr = [random.randint(1, 100) for _ in range(10)]
print("Original:", arr)
bubble_sort(arr)
print("After sort:", arr)
# Original: [45, 27, 76, 30, 59, 52, 80, 75, 99, 6]
# After sort: [6, 27, 30, 45, 52, 59, 75, 76, 80, 99]
Complexity
Type | Complexity |
---|---|
Time | Best: O(n) |
Average: O(n) | |
Worst: O(n^2) | |
Space | Worst: O(1) |
Stability
Stable