Bubble Sort in JavaScript for Beginners

Fanzhong Zeng
3 min readJun 18, 2020

--

Bubble Sort, the most common sorting algorithm that everyone learns at the beginning. Usually it is the introduction that professors will use to teach beginner programmers about algorithms in coding as the logic is simply and can easily be implemented in any coding language within seconds.

The idea behind bubble sort is that it’ll compare adjacent element and swap them if they are in the wrong order. This way all the element will slowly swap into the correct order one space at a time. Then it’ll repeat this process for a maximum of the amount of time as the length of the array.

Bubble Sort in JavaScript

The first step of bubble sort is to find the length of the array you want to sort. Because this will be the worse case scenario that you’ll need to run. So we’ll set up a for loop for the maximum amount of time the array will run. Then we also need another for loop go to through all the elements in the array and compare them to the next element to see if anything needs to be moved.

A small trick to optimize this is that for the second loop, you can do length-1. As when you reach the last element of the array, there is no more elements for you to do comparison with. Therefor we can just ignore the last element and we don’t have to compare it.

Now all we need is to grab the current elements and compare it to the next element. If the first element is smaller than the second, we swap them. Of course you can also do the reverse if you want it to be from bigger to smaller. With this we are done with bubble sort and we can just return the result.

Another small thing you can do is to only use one temp variable to store the data and you can just override one element of the array by another element.

However this will increase the amount of time you have to get data from the array by once, and if the array is really large, it might affect the speed of the search by a bit. (like maybe a few milliseconds, though if you really cared about speed, bubble sort is probably the worse algorithm to use)

One more optimizing trip you can do is to do a conditional break to break out the first loop. If we only ran the array 2 times and we already sorted the array in order, do we really need to run the array X amount of times as the array’s length? Therefore we can introduce a variable to see if any change was made, and if there isn’t we can break out the entire loop.

Non-Destructive Bubble Sort

Though one thing you should note is that, in JavaScript there is destructive and nondestructive functions. The above code changes the original array and depending on what you need, you might not want it to change the original array. Therefore you can use the spread operator … to create another array and modify that new array instead.

Here for the Code Only?

Version 1: Destructive Bubble Sort

Version 2: Non-Destructive Bubble Sort

--

--

Fanzhong Zeng
Fanzhong Zeng

No responses yet