Bubble Sort

Kulani Baloyi / May 22, 2024

2 min read

It's a basic sorting technique that's easy to understand and implement, but not the most efficient for large datasets.


What is Bubble Sort?

In computer science, Bubble Sort works similarly. It takes an unsorted list of elements (numbers, words, etc.) and arranges them in a specific order, typically ascending (smallest to biggest) or descending (biggest to smallest).

How Does Bubble Sort Work?

Here's a step-by-step breakdown:

Start at the beginning: We iterate through the list, comparing each element with its neighbor to the right. Compare and Swap: If the current element is greater than its neighbor, we swap their positions. Think of pushing the bigger item towards the end of the list. Repeat and refine: We continue iterating through the list, making swaps as needed. With each pass, the largest element "bubbles" up to its rightful place at the end. Continue until sorted.

Bubble Sort in Action

Unsorted List: [6, 4, 2, 8, 1]

Pass 1: Compare 6 and 4, swap. Now: [4, 6, 2, 8, 1]
Pass 2: Compare 6 and 2, swap. Now: [4, 2, 6, 8, 1]
Pass 3: Compare 2 and 8, no swap needed.
Pass 4: Continue comparing elements, making swaps as needed.

Sorted List: [1, 2, 4, 6, 8]

Bubble sort has a time complexity of O(n^2), which means the sorting time increases quadratically with the number of elements (n). This makes it slow for large datasets.

Related articles:

Dijktras Algorithm
Jul 15, 2024
Depth First Sort
Jul 12, 2024
Orders of growth
Jul 3, 2024
Binary Search
May 21, 2024
Insertion Sort
May 21, 2024