The Bubble Sort
BubbleSort(array, start, stop)
- for end = stop; end > 0; end--
- for i = start; i < end; i++
- if array[i] > array[i+1]
- swap (array[i], array[i+1])
- return
- Trace this with 8 3 5 6 2 7 4
end i array
6 0 3 8 5 6 2 7 4
1 3 5 8 6 2 7 4
2 3 5 6 8 2 7 4
3 3 5 6 2 8 7 4
4 3 5 6 2 7 8 4
5 3 5 6 2 7 4 8
5 0 3 5 6 2 7 4 8
1 3 5 6 2 7 4 8
2 3 5 2 6 7 4 8
3 3 5 2 6 7 4 8
4 3 5 2 6 4 7 8
4 0 3 5 2 6 4 7 8
1 3 2 5 6 4 7 8
2 3 2 5 6 4 7 8
3 3 2 5 4 6 7 8
3 0 2 3 5 4 6 7 8
1 2 3 5 4 6 7 8
2 2 3 4 5 6 7 8
2 0 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 0 2 3 4 5 6 7 8
- Notice the the biggest numbers sort of "bubble" to the end.
- But at the same time, the smaller numbers "bubble" down to the other end.
- An improvement is immediately visiable
BetterBubble(array, start, stop)
- swapped = true
- end = stop;
- while swapped
- swapped = false;
- for i = start; i < end; i++;
- if array[i] > array[i+1]
- swap (array[i], array[i+1])
- swapped = true
- end --
- return
- This will allow us to quit once the array is in order.
- What is the best case performance for this sort?
- If the array is in complete order, swapped will be set to false on line 4 and will not be changed, as the test in line 6 will never be true
- Thus the loop (3-9) will execute 1 time
- The loop (5-8) will execute n times
- The entire algorithm is O(n).
- How about the worst case?
- What happens with the inner loop?
- What will happen with the outer loop?
- What happens if we sor a mostly in order array?
4 2 3 1 7 5 6 8 9 11 12 14
2 3 1 4 5 6 7 8 9 11 12 14 (after 1 pass of lines 5-9)
- Notice, that we know that the array from 7 on was in order
since no swaps occured after the swap of 7,6
- We could move end to this position now couldn't we?
BetterYetBubble(array, start, stop)
- swapped = true
- end = stop;
- while swapped
- swapped = false;
- for i = start; i < end; i++;
- if array[i] > array[i+1]
- swap (array[i], array[i+1])
- swapped = true
- quit = i
- end = quit;
- return
- In the worst case, end is decreased by 1 each time as before (and the sort is still O(n2))
- In other cases we can quit early if the end of the array is already sorted. (but we still don't get any better than O(n))
- The average time analysis of bubblesort is somewhat beyond the scope of this class, but turns out to be O(n2).
- In all but the best cases, bubble sort is horrid, and should not be used.
So why did we look at it?
- Again, we see that by looking at an algorithm we can tune it's performance
- This is a classic algorithm, that is worth looking at.