Section 22.4 Bubble Sort
Have you ever needed to sort a pile of papers into alphabetical order? There are many different ways to do so and you yourself may have a preferred method. But could you teach that method to a computer? A sorting algorithm is just that: it is an algorithm that puts elements of a list in a certain order. Most of the time we’ll want to sort data numerically (from smallest to largest or from largest to smallest) or alphabetically. In order to sort small amounts of data efficiency isn’t really all that important, but when lists get long then it is important to pay attention to the efficiency of the algorithms. That’s why there are many different sorting algorithms that have been invented and we’ll just scratch the surface and study some of the simple (and not very efficient) ones.
Most sorting algorithms have names that somewhat refer to how they function. Some of the simple algorithms include the so-called Selection Sort and Insertion Sort, some more efficient algorithms include Quick Sort and Merge Sort. And then there is the Bubble Sort category which is very easy to implement and understand (and not all that efficient). We will learn about Bubble Sort first and then also implement Selection Sort and Insertion Sort in class.
If you cannot see this codecast, please click here.
The animation below might help you visualize how bubble sort functions.
Check Your Understanding Check Your Understanding
2.
Complete the following C program so that it correctly sorts the given array from smallest to largest using bubble sort. In particular, you need to complete the function
bubbleSort()
below which handles the sorting. Everything else has been done for you already.
When your program performs correctly you’ll be given a keyword to enter in Canvas.
3.
Suppose that you have made the following declarations:
int num[] = {5,3,7,9,2,4,6};
int index[] = {2,3,4,5,6,7,1};
What is
index[3]
? Choose one: 1 / 2 / 3 / 4 / 5
What is
num[index[3]]
? Choose one: 2 / 3 / 4 / 5 / 6 / 7 / 9
Feel free to use the window below to try out some code. Be sure to work the correct answer out "by hand" first before verifying your answer using the code window.
Enter your two answers, separated by a comma, i.e. 8, 1