Algorithm:
Stable: yes
Python Implementation
def bubble_sort(array):
n = len(array)
for j in range(n):
for i in range(n-1-j):
if a[i] > a[i+1]:
a[i+1], a[i] = a[i], a[i+1]
- Start at the beginning
- Swap first two element if first is greater than second
- Continue to next pair
- Repeat until sorted
- Best: O(n) - when the list is already sorted
- Worst: O(n2) - when required to reverse the list
- O(1) - usually no extra space is required
Stable: yes
Python Implementation
def bubble_sort(array):
n = len(array)
for j in range(n):
for i in range(n-1-j):
if a[i] > a[i+1]:
a[i+1], a[i] = a[i], a[i+1]
No comments:
Post a Comment