Bubble Sort in Python
Introduction
For most people, Bubble Sort is likely the first sorting algorithm they heard of in their Computer Science course.
It’s highly intuitive and easy to “translate” into code, which is important for new software developers so they can ease themselves into turning ideas into a form that can be executed on a computer. However, Bubble Sort is one of the worst-performing sorting algorithms in every case except checking whether the array is already sorted, where it often outperforms more efficient sorting algorithms like Quick Sort.
Bubble Sort
The idea behind Bubble Sort is very simple, we look at pairs of adjacent elements in an array, one pair at a time, and swap their positions if the first element is larger than the second, or simply move on if it isn’t. Let’s look at an example and sort the array 8, 5, 3, 1, 4, 7, 9:
If you focus on the first number, the number 8
, you can see it “bubbling up” the array into the correct place. Then, this process is repeated for the number 5
and so on.
Implementation
With the visualization out of the way, let’s