English

nu

Searching & Sorting: Faster Ways to Find Things

guest
0 / ?
back to lessons

Swapping Neighbors into Order

Bubble Sort: Compare Neighbors & Swap

Bubble Sort: each pass swaps out-of-order neighbors, bubbling the largest to the end

Bubble sort puts a list in order by comparing two neighboring items at a time.

If two neighbors are out of order — swap them.

Keep making passes through the list until nothing needs swapping.

Example: sort [5, 3, 8, 1]

Pass 1:

- Compare 5 & 3. 5 > 3, so swap → [3, 5, 8, 1]

- Compare 5 & 8. 5 < 8, no swap → [3, 5, 8, 1]

- Compare 8 & 1. 8 > 1, so swap → [3, 5, 1, 8]

Pass 2:

- Compare 3 & 5. OK → [3, 5, 1, 8]

- Compare 5 & 1. 5 > 1, swap → [3, 1, 5, 8]

- Compare 5 & 8. OK → [3, 1, 5, 8]

Pass 3:

- Compare 3 & 1. 3 > 1, swap → [1, 3, 5, 8]

- Compare 3 & 5. OK. Compare 5 & 8. OK.

Done! [1, 3, 5, 8] ✓

Notice: the biggest number bubbles to the end of the list on each pass. That is how bubble sort gets its name.

Bubble sort works. It is not the fastest for big lists, but it is easy to understand — perfect for learning.

Sort [4, 2, 7, 1] with Bubble Sort

Sort this list using bubble sort: [4, 2, 7, 1]

Show the list after each pass. Count how many passes it takes to finish.

Sort [4, 2, 7, 1] using bubble sort. Show the list after each complete pass, and tell me how many passes it takes.