Test your knowledge with free interactive questions on Seneca — used by over 10 million students.

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, 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.
In English

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.
Example

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.
Pros and cons of bubble sort

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
1

Computer Systems

1.1

Systems Architecture

1.2

Memory & Storage

1.3

Computer Networks, Connections & Protocols

1.4

Network Security

1.5

Systems Software

1.6

Ethical, Legal, Cultural & Environmental Concern

2

Computational Thinking, Algorithms & Programming

2.1

Algorithms

2.2

Programming Fundamentals

2.3

Producing Robust Programs

2.4

Boolean Logic

2.5

Programming Languages & IDEs

Practice questions on Bubble Sort

Can you answer these? Test yourself with free interactive practice on Seneca — used by over 10 million students.

  1. 1
  2. 2
  3. 3
Answer all questions on Bubble Sort

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