A Beginner's Guide to Bubble sort Algorithm with Javascript Example
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
The algorithm starts by comparing the first two elements of the array. If the first element is larger than the second, the two elements are swapped. The algorithm then moves on to the next pair of elements and repeats the process.
This process continues until the end of the array is reached. The outer loop then starts again, this time starting at the beginning of the array and continuing until the end. It makes sure that the largest element is "bubbled up" to the end of the array in each pass. The inner loop is used to compare adjacent elements and if they are in the wrong order, they are swapped.
It is important to note that bubble sort has a time complexity of O(n^2) in worst-case and average case and O(n) in best case(when the array is already sorted) and it is not efficient for large datasets. It is simple to understand and easy to implement but not recommended for production use.
Here is an example of bubble sort implemented in JavaScript:
function bubbleSort(arr) {
let swapped;
do {
swapped = false;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
}
while (swapped);
return arr;
}
console.log(bubbleSort([5, 3, 6, 2, 10]));
This implementation uses a "do-while" loop that continues to loop as long as a swap has been made during the previous pass. The inner "for" loop compares each element to the one that comes after it, and if they are out of order, they are swapped. This process continues until no more swaps are needed, indicating that the array is now sorted.
It is to be noted that bubble sort has a time complexity of O(n^2) in worst-case and average case and O(n) in best case(when the array is already sorted) and it is not efficient for large datasets. It is simple to understand but not recommended for production use.
In summary, the Bubble sort algorithm repeatedly steps through the list, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
Comments
Post a Comment