Seneca

Bubble Sort

Computer Science: OCR GCSE, topic 2.1.13

Bubble Sort

Bubble sort is a naive sorting algorithm.

The concept

The concept

  • Imagine that you have a set of cards face up on the desk.
  • If the first two cards are in the wrong order, you swap them.
  • Then do the same for the second and third cards.
  • Continue in the same pattern until the end of the pack.
  • Repeating the pattern across the whole pack once is called a pass.
  • The highest value will 'bubble' up to the top of the pack each pass.
  • By repeating these passes enough times, the pack will get sorted.
In English

In English

  • Compare the first two items of the dataset:
  • Swap the two items if they aren't in the right order.
  • Continue for the rest of the cards in the deck.
  • Repeat the whole process, until a pass with no swaps happens.
In pseudocode

In pseudocode

Example

Example

  • We will sort this list in ascending order:
  • [7, 3, 9, 2, 5]
  • Step 1:
  • Compare 7 and 3
  • 7 > 3 → swap
  • [3, 7, 9, 2, 5]
  • Step 2:
  • Compare 7 and 9
  • 7 < 9 → no swap
  • [3, 7, 9, 2, 5]
  • Step 3:
  • Compare 9 and 2
  • 9 > 2 → swap
  • [3, 7, 2, 9, 5]
  • Step 4:
  • Compare 9 and 5
  • 9 > 5 → swap
  • [3, 7, 2, 5, 9]
  • At the end of the first pass, the largest value (9) has “bubbled up” to the final position.
Pros and cons of bubble sort

Pros and cons of bubble sort

  • Pros:
  • More memory efficient than the merge sort.
  • Bubble sort does not need to use an extra space during the algorithm.
  • All swaps happen 'in place'.
  • The algorithm is easy to implement.
  • Cons:
  • Often slower than the insertion sort on a dataset of the same size.
  • On average, more comparisons are required.

Test yourself on Bubble Sort

  • What is a disadvantage of bubble sort compared to insertion sort?

  • Bubble Sort in English

  • In bubble sort, two adjacent items are compared and the left item is smaller than the right item. What happens to these two items?

Practise this topic for free