Daniel C Reyes

Jan 3, 2021

2 min read

Bursting the Bubble (sort)

Understanding Bubble Sort

As I continue to dive in data structures and algorithms the realization that sorting algorithms play a major role in programming is becoming clearer and clearer. A sorting algorithm arranges the elements in a collection of data in the right order. It is often useful while programming, as it is useful in locating elements and merging elements. One of the most useful and simplest sorting algorithms used is the Bubble Sort.

Bubble sort is the sorting algorithm will iterate through all the elements and compares each of the elements with its adjacent element and swap if it is not in order. The larger valued element bubble up to the end of the data collection through each iteration and hence the name bubble sort. So, if you had an array with [ 5 ,1, 4, 2, 8] the bubble sort function would compare 5 to 1 then compare 5 to 4 and so on until the array is sorted. Down below is an example and explanation on how this the bubble sort works.

First Iteration thru the data:
( 5 1 4 2 8 )=> ( 1 5 4 2 8 ) Here, bubble sort compares the first
two elements, and swaps since 5 greater than 1.
( 1 5 4 2 8 ) =>( 1 4 5 2 8 ) Swap since 5 greater than 4
( 1 4 5 2 8 ) =>( 1 4 2 5 8 ) Swap since 5 greater than 2
( 1 4 2 5 8 ) =>( 1 4 2 5 8 ) Now, since these elements are already in order (8 less than 5), algorithm does not swap them.
Second Iteration thru data:
( 1 4 2 5 8 ) =>( 1 4 2 5 8 )
( 1 4 2 5 8 ) =>( 1 2 4 5 8 ) Swap since 4 greater than 2
( 1 2 4 5 8 ) =>( 1 2 4 5 8 )
( 1 2 4 5 8 ) => ( 1 2 4 5 8 )
Now, the array is already sorted, but the bubble sort does not know if it is complete. The bubble sort needs one whole iteration without any swap to know it is sorted.
Third Iteration and Final thru data:
( 1 2 4 5 8 ) =>( 1 2 4 5 8 )
( 1 2 4 5 8 ) =>( 1 2 4 5 8 )
( 1 2 4 5 8 ) =>( 1 2 4 5 8 )
( 1 2 4 5 8 ) =>( 1 2 4 5 8 )
const bubbleSort = array => {
let sorted;
do {
sorted = false;
for (let i = 0; i < array.length; i++) {
if (array[i] > array[i + 1]) {
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
sorted = true;
}
}
} while (sorted);
return array;
};

The Bubble Sort is a simple and very important way to get data in the order from lowest to highest.