Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Visualizer › Sorting

Bubble Sort

Repeatedly compares neighbouring elements and swaps them when they are in the wrong order, so the largest element "bubbles" to the end after each pass.

How it works

Complexity

Code (Python)

def bubble_sort(a):
    n = len(a)
    for i in range(n - 1):
        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:      # already sorted
            break
    return a

Practise: Arrays problems