Bubble Sort For absolute Beginners
Bubble Sort is a simple sorting algorithm that compares adjacent elements and swaps them if they are in the wrong order. It’s called “bubble” sort because smaller elements “bubble” to the top of the list. It’s a great starting point for understanding sorting algorithms, but it’s not the most efficient for large datasets.
See it in action
Code
bubble-sort.ts
function bubbleSort (dataset: number[]) {
let n = dataset.length;
/**
* Loop #1: Loop through the entire dataset once, because every time we go through the dataset,
* the largest element will be at the end of the dataset and we can ignore it in the next iteration
*/
while (n > 0) {
/**
* Loop #2: Loop through the dataset again but ignore the last element
* because it is already sorted
*/
for (let i = 0; i < n - 1; i++) {
// Compare the current element with the next element and swap if necessary
if (dataset[i] > dataset[i + 1]) {
[dataset[i], dataset[i + 1]] = [dataset[i + 1], dataset[i]];
}
}
n--;
}
};
Why Use Bubble Sort?
Bubble Sort is easy to understand and implement, making it a great choice for beginners. It’s also useful for small datasets or when you need a simple sorting solution without the complexity of more advanced algorithms. However, for larger datasets, more efficient algorithms like Quick Sort or Merge Sort are recommended.
Key Points
- Simple to understand: Bubble Sort is one of the simplest sorting algorithms, making it a great starting point for beginners.
- Inefficient for large datasets: Bubble Sort has a time complexity of O(n^2) in the average and worst cases, making it inefficient for large lists.
- Stable sort: Bubble Sort is a stable sorting algorithm, meaning that it maintains the relative order of equal elements.
- In-place sort: Bubble Sort requires only a constant amount of additional memory space, making it an in-place sorting algorithm.
- Adaptive: Bubble Sort can be optimized to stop early if the list is already sorted, making it more efficient in some cases.