|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Bubble Sort
Because of bubble sort's simplicity, it is one of the oldest sorts
known to man. It based on the property of a sorted list that any
two adjacent elements are in sorted order. In a typical iteration of
bubble sort each adjacent pair of elements is compared, starting with
the first two elements, then the second and the third elements, and all
the way to the final two elements. Each time two elements are
compared, if they are already in sorted order, nothing is done to them
and the next pair of elements is compared. In the case where the two
elements are not in sorted order, the two elements are swapped, putting
them in order.
Consider a set of data: 5 9 2 8 4 6 3. Bubble sort first compares the
first two elements, the 5 and the 6. Because they are already in
sorted order, nothing happens and the next pair of numbers, the 6 and
the 2 are compared. Because they are not in sorted order, they are
swapped and the data becomes: 5 2 9 8 4 6 3. To better understand the
"bubbling" nature of the sort, watch how the largest number, 9,
"bubbles" to the top in the first iteration of the sort.
(5 9) 2 8 4 6 3 --> compare 5 and 9, no swap
5 (9 2) 8 4 6 3 --> compare 9 and 2, swap
5 2 (9 8) 4 6 3 --> compare 9 and 8, swap
5 2 8 (9 4) 6 3 --> compare 9 and 4, swap
5 2 8 4 (9 6) 3 --> compare 9 and 6, swap
5 2 8 4 6 (9 3) --> compare 9 and 3, swap
5 2 8 4 6 3 9 --> first iteration complete
The bubble sort got its name because of the way the biggest elements
"bubble" to the top. Notice that in the example above, the largest
element, the 9, got swapped all the way into its correct position at
the end of the list. As demonstrated, this happens because in each
comparison, the larger element is always pushed towards its place at
the end of the list.
In the second iteration, the second-largest element will be bubbled up
to its correct place in the same manner:
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Contact Us | Privacy Policy | Terms and Conditions | About
©2006 SparkNotes LLC, All Rights Reserved.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||