Describe the process of Bubble Sort and its time complexity.
Instruction: Explain how Bubble Sort works and discuss its average and worst-case time complexities.
Updated
Official answer
Bubble sort compares adjacent elements and swaps out-of-order pairs. In a left-to-right pass, the largest remaining value reaches the end of the unsorted region. This Python variant stops early if a pass makes no swaps:
def bubble_sort(a):
for end in range(len(a) - 1, 0, -1):
swapped = False
for j in range(end):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return a
It mutates and returns the list. Swapping only strictly greater adjacent elements makes it stable for equal keys. It needs O(1) auxiliary space under constant-cost comparisons and swaps.
Worst-case and average-case time on random distinct permutations are O(n²). A reverse-sorted list takes n(n-1)/2 comparisons in this loop structure. Already sorted input takes one pass, O(n), because of the early-exit check; a variant without that check still does quadratic comparisons. Empty and single-element lists need no comparisons.
Bubble sort is mainly useful for explaining invariants and simple sorting mechanics. Use a suitable library sort for ordinary application work rather than assuming this simple implementation is efficient for large inputs.