Welcome Gophers! In this lesson, we are going to have a look at the Bubble Sort algorithm — how it works, its time complexity, and its characteristics.
Overview
Now the first algorithm that we are going to be looking at within this course is the bubble sort algorithm.
The bubble sort algorithm is a comparision sorting algorithm that will repeatedly pass through a list and compare each element within the list against the next element. If the first element is greater than the next element then these elements will be swapped.
We then pass through this array until each element of the array is in its correct position.
It will then continue passing through this array until there are no swaps performed and we know that the array has been sorted.
How It Looks
Here’s a visual of one pass of bubble sort working through an array:
Time Complexity
Bubble Sort is simple but not the fastest kid on the block:
- Best case: O(n) — when the array is already sorted (one pass, no swaps)
- Average case: O(n²) — nested comparisons add up quickly
- Worst case: O(n²) — when the array is reverse sorted
The space complexity is O(1) since we sort in place — no extra memory needed.
When to Use Bubble Sort
Bubble Sort is mostly useful as a teaching tool. In practice, you’d almost always reach for something faster like Quick Sort or Merge Sort. That said, it does have one nice property — if the array is already nearly sorted, it can finish in close to linear time thanks to the early exit when no swaps happen.
Quiz Time
Try your hand at these questions to validate what you’ve learned:
