Search Menu


Bubble Sort Problems

Problem : Trace the operation of bubble sort on the following list: 4, 7, 2, 5, 6

The successive configurations of the list are as follows:
4, 7, 2, 5, 6 The starting configuration
4, 7, 2, 5, 6 4 < 7, so no swap is necessary
4, 2, 7, 5, 6 Swap the 2 and the 7 because 7 > 2
4, 2, 5, 7, 6 Swap the 5 and the 7 becuase 7 > 5
4, 2, 5, 6, 7 Swap the 6 and the 7 because 7 > 6. This is the end of the first pass. Notice how the 7 has "bubbled" up to the top of the list.
2, 4, 5, 6, 7 Swap the two and the 4 because 4 > 2. The list is now in sorted order; the algorithm will detect this on the next pass through the list when it makes no swaps.

Problem : What is the worst case scenario for bubble sort, and why?

The worst situation for bubble sort is when the list's smallest element is in the last position. In this situation, the smallest element will move down one place on each pass through the list, meaning that the sort will need to make the maximum number of passes through the list, namely n - 1.

Problem : What simple modification could be made to the bubble sort algorithm that would make it perform more efficiently on the case described above?

The algorithm could be made to start at the end of the list and move towards the front, swapping elements only if the first is greater than the second. In this way, the smallest numbers would bubble down instead of the large numbers bubbling up. Note however that this algorithm has its own worst case scenario that is just as bad as the worst case for the normal bubble sort. It occurs when the list's largest element is in the first position.

Problem : What would happen if bubble sort didn't keep track of the number of swaps made on each pass through the list?

The algorithm wouldn't know when to terminate as it would have no way of knowing when the list was in sorted order.