Skip to content
UPEEC

Bubble Sort

Repeatedly swap adjacent out-of-order elements until the list is sorted.

Beginner
Comments 0
def bubble_sort(a):
    n = len(a)
    for i in range(n):
        swapped = False
        for j in range(n - 1 - i):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        if not swapped:
            break        # already sorted

Simple to understand but O(n2)O(n^2) — fine for teaching and tiny arrays, too slow for real data.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.