Skip to content

Bubble sort

JavaScript nested loops + swap

Same task in: Python

Flowchart (ISO 5807)

YesNoStartInput ai = 0, |a| − 1, 1j = 0, |a| − i − 1 − 1, 1a[j] > a[j + 1][a[j], a[j + 1]] = [a[j + 1], a[j]]Return aEndFigure 1 — bubbleSort

Source code

JavaScript
function bubbleSort(a) {
    for (let i = 0; i < a.length; i++) {
        for (let j = 0; j < a.length - i - 1; j++) {
            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
JavaScript
Constructs
nested loops + swap
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples