An Overview of the Bubble Sort Algorithm in JavaScript
Sorting algorithms are an important topic to know if you’re doing technical interviews. While you may not ever use them on the job, employers want to know that you understand there are various ways to organize data. Here, we’ll take a look at one of the most popular algorithms: bubble sort.
A Word on “Big O”
Bubble sort’s runtime is quadratic, or O(n²), which means it is very slow and inefficient for large quantities of data. If the array is already sorted (best case scenario), bubble sort can improve to linear runtime, or O(n). However, you’re more likely to start with unsorted data, which would mean dealing with poor performance.
How It Works
Bubble sort functions by comparing two adjacent values, deciding which is higher, and swapping the order, if needed, so that the greater value is in the lead. This is accomplished with loops. So, for each loop through the array, the greater values get pushed towards the end in sorted order. You can think of it as the greater values “bubbling” to the top—hence the name.
Let’s take a look at some code to get a better understanding. We can start by setting up one loop with a variable i
that starts at the end of the array and runs back towards the beginning. Next, add a nested loop that runs from the beginning until i - 1
.
const bubbleSort = arr => { for(let i = arr.length; i > 0; i--){ for(let j = 0; j < i - 1; j++){ } }return arr}
Then, we want to create a condition to determine if one value is greater than the other. If so, we swap by reassigning variables and moving the larger value to the end.
const bubbleSort = arr => { for(let i = arr.length; i > 0; i--){ for(let j = 0; j < i - 1; j++){ if(arr[j] > arr[j + 1]){ //SWAP -- place large values on the end let temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } }return arr}
In its current state, the code above will sort the array, but we will run into one problem: The algorithm will continue to loop over the array searching for values to swap far after it has finished sorting. So, we want to limit it. We can achieve this by checking for swaps.

If no more swaps are running, then noSwaps will equal true, which means that the loop will break, and we will return our array.