Activity 10-5 steps through the algorithm for a bubble sort. You may want to gather 4 or 5 items of different sizes and practice sorting them yourself.
Below is the basic algorithm for a bubble sort that sorts in descending order. This description is called pseudo-code because although it is not give in code, it is more code-like than a language spoken by people. You can practically take each sentence and covert it to a programming language and have the algorithm coded.
Figure 10-5: Pseudo Code for the Bubble Sort Algorithm
Assume the list is not sorted (sorted is set to FALSE)
while(!sorted)
{
Assume the list is sorted (sorted is set to TRUE)
Set i to loop through list from first to last - 1
{
if list[i] and list[i + 1] are not in the right order
{
switch them (called a swap)
set sorted to FALSE
}
}
}
Notice that although the psuedo code does not contain Java-specific syntax,
it is somewhat clear to you how to write the code. We will not show the
code because it is one of your Programming Assignments at the end of this
module.
Let's go through the algorithm for a bubble sort.
Activity 10-6: Bubble Sort Algorithm (Descending)
Activity 10-6: Bubble Sort Algorithm (Ascending)
One way to remember the difference between the two sorts is that a bubble sort switches elements as it goes through the list, but a selection sort only swaps once each time through the list.