Unformatted text preview: 9.4 Sorting 291 compare Bob with Al and do not swap. If no values are swapped during an iteration, then the list is sorted. We set a Boolean variable to false before we enter the loop and set it to true if a swap occurs. If the Boolean variable is still false, then the list is sorted. Compare the processing of bubble sort to selection sort on an already sorted list. Selection sort makes no attempt to determine if the list is sorted; therefore, we will go through the entire algorithm.
Bubble Sort Set current to index of first item in the list Do Set swap to false “Bubble up” the smallest item in unsorted part Increment current to shrink the unsorted portion While (not yet sorted AND swap) Bubble up For index going from length 1 down to current + 1 If (list[index].compareTo(list[index 1]) < 0) Swap list[index] and list[index 1] Set swap to true items “Fz “z “9z “z “hz Al Bob Jim John Phil Figure 9.11 Example of an already sorted list. We used a posttest loop because at least one iteration is necessary to determine that the list is sorted even if the list is sorted to begin with. Quicksort
The Quicksort algorithm, developed by C. A. R. Hoare, is based on the idea that it is faster and easier to sort two small lists than one larger one. The name comes from the fact that, in general, Quicksort can sort a list of data elements quite rapidly. The basic strategy of this sort is to divide and conquer. If you were given a large stack of final exams to sort by name, you might use the following approach: Pick a splitting value, say L, and divide the stack of tests into two piles, A–L and M–Z. (Note that the two piles do not necessarily contain the same number of tests.) Then take the first pile and subdivide it into two piles, A–F and G–L. The A–F pile can be further broken down into A–C and D–F. This division process goes on until the piles are small enough to be easily sorted by hand. The same process is applied to the M–Z pile. ...
View Full Document