Bubble soft is the most straightforward sorting algorithm that works by repeatedly swapping the elements if they are in wrong orders.
Example:
1. Swapping the first element.
( 5
1 4 2 8 ) –> (
1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5
4 2 8 ) –> ( 1
4 5 2 8 ), Swap since 5 > 4
( 1 4 5
2 8 ) –> ( 1 4
2 5 8 ), Swap since 5 > 2
( 1 4 2
5 8 ) –> ( 1 4 2
5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
2. Swapping the second element.
(
1 4 2 5 8 ) –> (
1 4 2 5 8 ), No swap
( 1 4
2 5 8 ) –> ( 1
2 4 5 8 ), Swap since 4 > 2
( 1 2
4 5 8 ) –> ( 1 2
4 5 8 ), No swap
( 1 2 4
5 8 ) –> ( 1 2 4
5 8 ), No swap
3. Pass the sorting criteris when there is no swapping.
(
1 2 4 5 8 ) –> (
1 2 4 5 8 ), No swap
( 1
2 4 5 8 ) –> ( 1
2 4 5 8 ), No swap
( 1 2
4 5 8 ) –> ( 1 2
4 5 8 ), No swap
( 1 2 4
5 8 ) –> ( 1 2 4
5 8 ), No swap
Let write the code to do it:
let items = [1,2,3,5,4];
function bubbleSort(p_val){
let sorted = p_val;
for (let i=0, x=p_val.length; i<=x; i++){
let isSwapRequired = false;
for(let j=0; j<=x-i-1; j++){
// compare items and only swap them if the second one's smaller
if (sorted[j] > sorted[j+1]) {
isSwapRequired = true;
let first = sorted[j];
let second = sorted[j+1];
sorted[j+1] = first;
sorted[j] = second
}
}
// IF no two elements were swapped by inner loop, then break
if (!isSwapRequired) { break; };
}
return sorted;
}
document.write(bubbleSort(items));
The best case is when the array is already sorted, and worst case is the array is reverse sorted.
So that is the famous bubble sort. I will talk on other sorting algorithms next time.
Notes: There is a native javascript method to sort an array (Array.sort) that is more efficient and easier to use. This example is to demonstrate the bubble sort.