Bubble sort can be improved. Smart bubble sort keeps track of how many exchanges are done within any single pass through the unsorted section of the list. If no exchanges occur, then the list is sorted and the algorithm should stop.
a. Write a pseudocode version of the smart bubble sort algorithm.
b. Perform a smart bubble sort on the following list. How many comparisons are required?
$$
7,4,12,9,11
$$
c. Describe the best-case scenario for smart bubble sort on an n-element list. How many comparisons are required? How many exchanges are required?
d. Under what circumstances does smart bubble sort do the same number of comparisons as regular bubble sort?
Exercises 15-17 refer to still another sorting algorithm, called mergesort. Mergesort breaks the list to be sorted into smaller and smaller lists until there is just a bunch of one element (and thus obviously sorted) lists, then assembles the smaller sorted lists back together into larger and larger sorted lists. Here is a pseudocode version:
1. Get values for $n$ and the $n$ list items
2. While the current list has more than 1 item, do Steps 3 through 6
3. Split the list into two halves
4. Sort the first half of the list using mergesort
5. Sort the second half of the list using mergesort
6. Merge the two sorted halves $A$ and $B$ into $a$ new sorted list $C$ by comparing the next two items from $A$ and $B$ and always choosing the smaller value to go into $C$
7. Stop
Mergesort works by using the result of mergesort on two smaller lists, so mergesort, like the Fibonacci sequence in Exercise 3, is a recursive algorithm.
Step 6 in this algorithm deserves an example. Suppose that at one point in running mergesort we have two sorted lists $A$ and $B$, as follows:
$$
A=2,9 \quad B=6,7
$$
To create $C$, we compare 2 from $A$ and 6 from $B$.
Because 2 is smaller, it is removed from $A$ and goes into $C$.
$$
A=9 \quad B=6,7 \quad C=2
$$
Now compare 9 from $A$ and 6 from B. Because 6 is smaller, it is removed from $B$ and goes into $C$.
$$
A=9 \quad B=7 \quad C=2,6
$$
Comparing 9 and 7 results in
$$
A=9 \quad B=\quad C=2,6,7
$$
Finally, let us agree to count comparing 9 to nothing as a legitimate, if trivial, comparison resulting in 9 , which is added to $C$, the final sorted list.
$$
A=B=\quad C=2,6,7,9
$$