Sorting is the process through which data are arranged according to their values. There are several sorting algorithms or methods that can be used to sort data. Some include:
We will not be covering the selection or insertion sort methods in this module.
The bubble sort is an easy way to arrange data in ascending or descending order. If an array is sorted in ascending order, it means the values in the array are stored from lowest to highest. If values are sorted in descending order, they are stored from highest to lowest. Bubble sort works by comparing each element with its neighbor and swapping them it they are not in the desired order. 1
There are several different methods of bubble sorting and some methods are more efficient than others. Most use a pair of nested loops or iteration control structures. One method sets a flag that indicates that the array is sorted, then does a pass and if any elements are exchanged (switched); it sets the flag to indicate that the array is not sorted. It is executed until it makes a pass and nothing is exchanged.
The bubble sort gets its name from the lighter bubbles that move or "bubble up" to the top of a glass of soda pop. We move the smaller elements of the array to the top as the larger elements move to the bottom of the array. This can be viewed from a different perspective. Using an Italian salad dressing with oil, water and herbs; once shaken you can either:
- envision the lighter oil rising to the top; OR
- envision the heaver water and herbs sinking to the bottom
Either way is correct and this version of the code simply demonstrates the sinking to the bottom the heaver or larger elements of the array.
Bubble sorting is demonstrated in the demo file provided, thus you need to study this material in conjunction with the demo program.