Skip to content

Bubble sort

Python nested loops + swap

Same task in: JavaScript

Flowchart (ISO 5807)

YesNoStartInput an = |a|i = 0, n − 1, 1j = 0, n − i − 1 − 1, 1a[j] > a[j + 1]a[j], a[j + 1] = a[j + 1], a[j]Return aEndFigure 1 — bubble_sort

Source code

Python
def bubble_sort(a):
    n = len(a)
    for i in range(n):
        for j in range(n - i - 1):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
    return a

The editor opens with this code — change it and the chart redraws.

Language
Python
Constructs
nested loops + swap
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples