Bubblesort re-arranges the elements of a sequence {a1, a2, ... , an} to put them into ascending order:
The Compare-Exchange Operation: Bubblesort performs a number of compare-exchange operations. Each compare-exchange operation compares two adjacent elements of the sequence, and exchanges them if they are out of order. We denote this compare-exchange operation by CE(x, y). The pseudocode for the compare-exchange operation is:
|
Get the values of x and y if x > y then Set the value of temp to x Set the value of x to y Set the value of y to temp |
Knuth Diagrams: A good way to illustrate Bubblesort is with a Knuth diagram. Each element of the sequence is shown with a horizontal line and each compare-exchange operation is shown with a vertical line connecting the horizontal lines of the two elements it is treating. The unsorted sequence enters at the left side of the diagram and the sorted sequence exits at the right side of the diagram.
The following Knuth diagram shows how Bubblesort sorts a sequence of eight elements, a1, a2, ..., a8:
Pass 1 performs seven CE operations:
In a similar manner, Pass 2 moves the largest value of a1, a2, ..., a7 up into a7; Pass 3 moves the largest value of a1, a2, ..., a6 up into a6; and so on, until finally, Pass 7 moves the the largest value of a1 and a2 into a2 to complete the sort of the 8-element sequence.
The pseudocode for Bubblesort is shown below:
|
Get the length of the sequence, n Get the elements in the sequence, a1, a2, ... , an Set the value of i to (n - 1) while i > 1 do Set the value of j to 1 while j < i do CE(aj, aj+1) Add 1 to the value of j Subtract 1 from the value of i |
Note that the only action that the exchanges in each Bubblesort-pass must perform is to move the largest value of a sub-sequence up into the last element of that sub-sequence: all other exchanges the pass performs are wasted effort.
Selection Sort eliminates the wasted effort of Bubblesort. On an n-element sequence it performs n-1 passes, (the same as Bubblesort) but it splits each pass up into two parts:
|
Get the length of the sequence, n Get the elements in the sequence, a1, a2, ... , an Set the value of i to n while i > 1 do Set the value of m to 1 Set the value of max to a1 Set the value of j to 2 while j < i do if max < aj then Set the value of m to j Set the value of max to aj Add 1 the value of j Set the value of am to ai Set the value of ai to max Subtract 1 from the value of i |