Menu

JavaScript Bubble Sort Algorithm Explained: A Beginner’s Guide

JavaScript Bubble Sort Algorithm Explained: A Beginner’s Guide

Sorting is a common task that comes up very frequently in the programming world. You need to sort things such as search result sets to standard lists of numbers, for reporting and such. The Bubble sort is probably the simplest of the sorting algorithms that you can implement and it is also a very popular question that is often asked during coding interviews.

Here is the full implementation of the Bubble Sort Algorithm, followed by a full breakdown of how it works.

JavaScript implementation

var numbers = [3, 4, 60, 20, 2, 0];

function BubbleSort(numbers)
{
    let isSwapped = true;

    while(isSwapped)
    {
        isSwapped = false;
        for (let i = 0; i < numbers.length - 1; i++)
        {
            if (numbers[i] > numbers[i+1])
            {
                isSwapped = true;

                let tmp = numbers[i+1];
                numbers[i + 1] = numbers[i];
                numbers[i] = tmp;
             }
         }
    }

    console.log(numbers);
}

How the Bubble Sort algorithm works

For the sake of this example, let us assume that we are working on sorting a typical list of numbers in an array.

var numbers = [3, 5, 200, 30, 1, 4];

The Bubble Sort algorithm will essentially compare values that are next to each other starting from the first value and moving right: [0, 1], [1, 2], [2, 3], etc. If we are sorting by numeric value for example in descending order, the algorithm would begin by comparing [3, 5] from the array defined above. If they indeed match the criteria, meaning that the first value is greater than the second, then you would swap those two values and continue with a sequential matching on the next two numbers.

The function itself is controlled by a primary while loop that will run forever, until it has detected a 'no swap' scenario. For that reason, it is important to make sure that the control variable isSwapped is set correctly, as it has the potential for an infinite loop situation.

The inner for loop itself will iterate from from the starting position of 0, all the way to n - 1, with n being the size of the dataset. We stop 1 index short, since we are comparing the current value with its sequential 'n + 1' sibling.

Looking at Bubble Sort performance

The Bubble Sort algorithm has a worst-case scenario of 0(n^2) (big 0 notation), in which 'n' is the number of numbers that will need to be sorted. The benefit of the bubble sort, however, is that it has a built-in check for when the list is completely sorted and will let us know almost immediately with the isSwapped variable.

If the list is relatively close to being sorted from the start, then the performance on this algorithm is overall pretty good. On a list that is completely unsorted however, the performance isn't ideal and there are more optimal choices.

For more optimal performance, you would typically gravitate more towards a Quick Sort or a Merge Sort, both of which have average time complexities of 0(n log n). 

Common use cases for Bubble Sort

Since the Bubble Sort algorithm isn't the most efficient, it isn't ideal for large dataset processing. However, it can still be useful in certain scenarios, particularly if you are working with smaller datasets.

Education purposes

One of the primary use cases for the Bubble Sort algorithm deals with education. Because it is relatively simple to implement and understand, Bubble Sort makes for a great introduction to new developers getting started with algorithms.

Once there is a firm understanding of this relatively simple implementation, other algorithms such as Merge Sorts and Quick Sorts can be understood more easily.

Interview questions

This is a popular interview question that gets asked alot, mainly because it is quick to implement, can be written in almost any language and is still somewhat complex enough where you would need to stop and think for a minute, if you are not familiar with the algorithm.

I've asked this question myself to potential candidates during interviews for both of those reasons, and sometimes even skilled developers have a hard time remember just how and where to swap values.

Nearly sorted lists

As mentioned above, if a list is close to being sorted and does not require as many permutations, the time complexity for Bubble Sort isn't a huge deal and because of its ease of implementation it can make for a great quick solution on smaller data sets.

In conclusion

Because its simple to implement and understand, the Bubble Sort algorithm is an essential introduction to the principles of algorithm design and optimization. It was the first sorting algorithm that I personally learned over 20 years ago and it is still one that comes up often enough when I interview candidates for development roles.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

A
Alex
12/26/2023 12:53:59 PM
Solid article!
B
Bob
12/26/2023 12:56:19 PM
Good implementation. Easy to follow.
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment