An introduction to Bubble Sorts
In this step, you’re going to look at a method of sorting lists called bubble sort.
The bubble sort algorithm is one of the simplest sorting algorithms to implement. It’s not a very widely used sorting algorithm, but is more often used as a teaching tool to introduce the concept of sorting. This means that virtually every student of computer science will, at some point or another, learn how bubble sort works.
In this step I’ll take a broad look at the bubble sort algorithm, try to explain how it works, and provide a visualisation of the algorithm in action. Later on you’ll learn why it is not the best algorithm to sort a million 32-bit integers.
Real-world examples of the bubble sort algorithm are hard to find. However, with a little imagination, you can see how a bubble sort might happen in a real situation.
Imagine there are five cars all travelling down a straight road. They are all being driven on cruise control, but each of the cars’ speeds have been set to slightly different values.
When a car is travelling faster than the car in front, it will overtake it, and occupy the slower car’s position in the traffic. This will keep happening, with each car switching positions with any slower car in front of it. Eventually the cars will sort themselves according to their speeds, with the fastest car being at the front of the queue of traffic.
This is in essence how bubble sort works.
I am going to look in a little more detail at what is going on with the algorithm when I use it to sort some data. In the following example, I will sort some different balls, used in a variety of sports, according to their size. I’ll start with the balls in a random order, lined up in a horizontal line.