Bubble Sort
suggest changeBubble sort compares each successive pair of elements in an unordered list and swaps the elements if they are out of order.
The following example illustrates bubble sort on the list {6,5,3,1,8,7,2,4} (pairs compared in each step are wrapped in **). A pair is swapped when the left value is greater than the right value:
{6,5,3,1,8,7,2,4}
{**5,6**,3,1,8,7,2,4} -- 6 > 5 -> swap
{5,**3,6**,1,8,7,2,4} -- 6 > 3 -> swap
{5,3,**1,6**,8,7,2,4} -- 6 > 1 -> swap
{5,3,1,**6,8**,7,2,4} -- 6 < 8 -> no swap
{5,3,1,6,**7,8**,2,4} -- 8 > 7 -> swap
{5,3,1,6,7,**2,8**,4} -- 8 > 2 -> swap
{5,3,1,6,7,2,**4,8**} -- 8 > 4 -> swap
After one iteration through the list, we have {5,3,1,6,7,2,4,8}. Note that the greatest unsorted value in the array (8 in this case) will always reach its final position. Thus, to be sure the list is sorted we must iterate n-1 times for lists of length n.
Graphic:
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents