[Math] Bubble Sort vs Shuttle Sort

algorithmssorting

When sorting a list of items, shuttle sort (the one taught in the A-Level Maths unit D1 by OCR, NOT Cocktail sort – see below) does no more than as many comparisons as bubble sort (they always do equal swaps, which is due to the nature of these algorithms). I wanted to know whether or not bubble sort could ever sort a list with fewer comparisons than shuttle sort.

I attempted to write a computer program to do it, but after getting both sorting algorithms to work but not an auto run through of inputs lists, I had to manually enter them…

The Shuttle sort I'm referring to is described as follows (laid out how the exam board lays it out):

1st pass: Compare the 1st and 2nd numbers in the list and swap if needed

2nd pass: Compare the 2nd and 3rd numbers in the list and swap if needed. If swapped, compare 1st and 2nd and swap if needed.

3rd pass: Compare 3rd and 4th number in the list and swap if needed. If swapped, compare 2nd and 3rd, swap if needed. If swapped, compare 1st and 2nd, swap if needed.

This process continues throughout the entire list.

Best Answer

To get the largest element in it's right place we need do perform $n-1$ comparisons so the total number of comparisons of a bubble sort is

$$B_n = n-1 + n-2 + \ldots + 2 + 1 = \frac{(n-1)n}{2}$$

Shuttle sort does a bubble sort on the first two elements, then on the first three elements and so on. When we are sorting in the $(k+1)$'th element $a_{k+1}$ we know that the first $k$ elements are already sorted so we can stop comparing elements when we hit an element that is equal to or smaller than $a_{k+1}$. This means that we only need at most one full pass through the list each time we add in another element giving us

$$S_n \leq 1 + 2 + 3 + \ldots + n-1 = B_n$$

The number of swaps will be the same in both cases.

Related Question