Sort Algorithms: Visualizing Bubble Sort

Dean
3 min readJul 23, 2020

Bubble Sort is by no means the best sort to use every case, but when being introduced to sorting algorithms, its probably the best and easiest one to wrap your head around.

So imagine you have an array of numbers that you need to sort from greatest to least:

The way that a Bubble Sort works is that, in order starting from the beginning of the array it compares the current index in the loop with the index in front of it.

If the index in front of it is less than the current index the loop is on, we switch the values…

and rinse and repeat for the next values:

The actual process for this requires a nested loop. One to iterate over the array the other to compare the indexes of the array.

//initial loop
for(let i = 0; i < array.length; i++){

//create a variable to hold the index value we'll use to swap
let maxIndex;
//create second loop to compare index values
for(let j = 0; j < array.length; j++){

//If current index is greater than the index ahead of it...
if(array[j] > array[j + 1]){
//we'll swap the values of the indexes!
maxIndex = array[j]
array[j] = array[j + 1]
array[j + 1] = maxIndex
}
return array
}

The Bubble sort is a great introduction into the world of algorithms solely based on the limited complexity of the algorithm. That being said, it does have its drawbacks. The algorithm requires that for every item within the array there would need to be another loop iteration added.

That means that even on its best day that the bubble sort would have a time complexity of O(n²), or rather for each item in your array the time it takes to complete your function will grow exponentially. Computers are very fast so for a loop like in the example above the time it takes can pretty much be instantaneous, but when working with hundreds of thousands of items in a array, this would be a loop you would want to stay away from unless you don’t mind waiting for your computer to do billions of operations.

--

--