2.1.13

Bubble Sort

Test yourself

Bubble Sort

Bubble sort is a naive sorting algorithm.

Illustrative background for The conceptIllustrative background for The concept ?? "content

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, and continue in this pattern until the end of the pack. This is known as a pass.
  • The highest value will 'bubble' up to the top of the pack each pass.
  • By repeating this enough times, the pack will get sorted.
Illustrative background for In EnglishIllustrative background for In English ?? "content

In English

  • Compare the first two items of the dataset:
    • Swap these 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.
Illustrative background for ExampleIllustrative background for Example ?? "content

Example

  • We will sort this list in ascending order:
    • [7, 3, 9, 2, 5]
    • A bubble sort pass compares each pair of adjacent items and swaps them if they are in the wrong order.
  • 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. Bubble sort always places the highest unsorted value at the end after each pass.
Illustrative background for Pros and cons of bubble sortIllustrative background for Pros and cons of bubble sort ?? "content

Pros and cons of bubble sort

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

Jump to other topics

1Computer Systems

1.1Systems Architecture

1.2Memory & Storage

1.3Computer Networks, Connections & Protocols

1.4Network Security

1.5Systems Software

1.6Ethical, Legal, Cultural & Environmental Concern

2Computational Thinking, Algorithms & Programming

2.1Algorithms

2.2Programming Fundamentals

2.3Producing Robust Programs

2.4Boolean Logic

2.5Programming Languages & IDEs

Unlock your full potential with Seneca Premium

  • Unlimited access to 10,000+ open-ended exam questions

  • Mini-mock exams based on your study history

  • Unlock 800+ premium courses & e-books

Get started with Seneca Premium