Bubble Sort in Action

Let’s walk through a complete example of Bubble Sort.

Assume we want to sort the array [4, 2, 7, 1, 3]. It’s currently out of order, and we want to produce an array that contains the same values in ascending order.

Let’s begin the first pass-through. This is our starting array:

images/speeding_up_your_code_with_big_o/bubble_sort_5.png

Step 1: First, we compare the 4 and the 2:

images/speeding_up_your_code_with_big_o/bubble_sort_6.png

Step 2: They’re out of order, so we swap them:

images/speeding_up_your_code_with_big_o/bubble_sort_7.png

Step 3: Next, we compare the 4 and the 7:

They’re in the correct ...

Get A Common-Sense Guide to Data Structures and Algorithms in JavaScript, Volume 1 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.