Search⌘ K
AI Features

Introduction to Bubble Sort

Explore how bubble sort algorithm sorts arrays by repeatedly swapping adjacent elements until no swaps are needed. Understand its process, implementation steps, and how it determines when the array is fully sorted.

We'll cover the following...

The algorithm starts with the first element in the array until the last element in the array, and keeps on doing so until there is one complete pass without swapping! This creates a “bubble” effect, hence the name.

We want the array [4, 2, 1, 3] to be sorted in ascending order.

  1. We go to the first element in the array, which is 4. The next element, 2, is smaller than 4, so they are in the wrong position. They swap, and we go to the next element.

  2. As the elements swapped, the current element is still 4. We compare it to its next element, which is 1. 1 is smaller than 4, so they swap.

  3. Again, the current element is 4, as the elements swapped. We compare it to its next element 3, which is smaller. They swap, and we’ve reached the end of the array. As this wasn’t a pass without swapping, it means that the array hasn’t been sorted yet, so we go back to the first element.

  4. Current element 2 is bigger than 1, they swap.

  5. Current element 2 is smaller than 3, no swapping.

  6. Current element 3 is smaller than 4, no swapping. Although we can see in the example that the array has been sorted, the algorithm only returns once there has been an entire pass without swapping!

  7. Current element 1 is smaller than 2, no swapping.

  8. Current element 2 is smaller than 3, no swapping.

  9. Current element 3 is smaller than 4, no swapping.

  10. An entire pass without swapping! We’ve successfully sorted the array, and the bubble sort algorithm returns.