Sorting

Problem shape

Beginner
4
8
15
16
23
42
Core idea

Repeatedly swap adjacent out-of-order elements until the largest values bubble right.

Step 1 / 5
Problem shape
Current lesson

Bubble Sort Lab

Sorting Beginner

Bubble Sort

Welcome to the Bubble Sort algorithm lab. Repeatedly swap adjacent out-of-order elements until the largest values bubble right. Use it when: Use only for teaching; rarely useful in production. The time complexity is O(n^2), and the space complexity is O(1). The pseudocode is: for pass from 0 to n - 1 for i from 0 to n - pass - 2 if a[i] > a[i + 1] swap a[i], a[i + 1] As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n^2)

Space

O(1)

Pseudocode

for pass from 0 to n - 1
  for i from 0 to n - pass - 2
    if a[i] > a[i + 1]
      swap a[i], a[i + 1]
Open deeper structure lesson
1.0x