Skip to content

Algorithms

Bubble Sort

O(n²) time (a loop inside another loop) · O(1) space. On a big list, this is painfully slow.

The idea, in plain English

Bubble sort sorts a shelf of books by height. You only ever swap two books that sit next to each other. Walk along the shelf and compare each pair. If the left book is taller, swap them. After each pass, the tallest book you touched ends up at the end.

How it works

  1. 1Compare the first two items. If they are in the wrong order, swap them.
  2. 2Move one step right and compare the next pair. Keep going until you reach the end.
  3. 3After each full pass, the largest item sits at the end. Repeat until you make no more swaps.

When you'd use it

You will almost never use this in real code — it is slow. But it is a great first sort to learn, because you can see exactly what happens at each step.

Common beginner mistakes

  • Looping one step too far, so you compare past the end of the list.
  • Using bubble sort in real projects. Use your language's built-in sort instead.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Before: 5 2 9 1 5 6
Sorted: 1 2 5 5 6 9

See it in motion

Watch it sortBubble sortO(n²) time (a loop inside another loop) · O(1) space. On a big list, this is painfully slow.

Ready. Press play to watch it sort.

0
Comparisons
0
Writes
0/27
Step
0.0s
Time
ComparingSwappingSorted

Not sure this is the right topic? See the learning paths → or where this leads →