Bubble Sort is one of the simplest sorting algorithms in computer science. Although it’s not the fastest or most efficient, it is often the first algorithm taught because it helps beginners understand fundamental ideas like comparison, swapping, and iteration.
Let’s break it down step-by-step.
Learn how to write computer programs
Bubble Sort is a comparison-based sorting algorithm that repeatedly goes through a list, compares adjacent elements, and swaps them if they are in the wrong order.
This process continues until the entire list is sorted.
It gets its name from the way larger elements “bubble” to the top (end of the list), and smaller elements sink to the bottom.
Imagine you have a row of numbers:
[5, 1, 4, 2, 8] Bubble Sort will:
Compare each pair:
[1, 5, 4, 2, 8][1, 4, 5, 2, 8][1, 4, 2, 5, 8]Largest element (8) moves to the end.
Repeat the process for the remaining elements:
[1, 2, 4, 5, 8]Next-largest element (5) is now correctly placed.
Bubble Sort keeps doing this until no more swaps are needed.
repeat
swapped = false
for i = 0 to n-2
if array[i] > array[i+1]
swap(array[i], array[i+1])
swapped = true
end for
until swapped == false
The swapped flag is used to optimize the algorithm so it stops early when the list is already sorted.
function bubbleSort(arr) {
let swapped;
do {
swapped = false;
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
// Swap
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
} while (swapped);
return arr;
}
console.log(bubbleSort([5, 1, 4, 2, 8]));
| Case | Time Complexity |
|---|---|
| Best Case (already sorted) | O(n) |
| Average Case | O(n²) |
| Worst Case | O(n²) |
| Space Complexity | O(1) (in-place) |
Because for each of the n elements, we might compare it with almost n others.
Even though it’s not efficient for large data, Bubble Sort is useful when:
Bubble Sort is the simplest sorting algorithm that repeatedly compares and swaps adjacent elements until the list is ordered. Though not efficient for large datasets, it is a perfect introduction to sorting concepts, complexity analysis, and algorithm design.
Latest tech news and coding tips.
Cybercriminals don't always announce their presence. Many compromises are designed to remain unnoticed for weeks…
For years, jQuery was everywhere. If you were building websites in the 2010s, there was a…
Few things halt a developer’s flow faster than seeing the dreaded word: CONFLICT. A Git merge…
Spring Boot is one of the most popular frameworks for building REST APIs in Java.…
Why borrowing code is a skill—when you understand what you're copying. For years, "copy-paste developer"…
Interactive forms rarely keep every field active all the time. Sometimes an input should only…