JavaScript Algorithms: Sort a list using Bubble Sort in 2024

2 min read
Last updated: Oct 13, 2024

Bubble Sort also known as sinking sort is one of the simplest algorithm for sorting, but inefficient with a complexity of O(n^2).

Algorithm:

  • Loop through an array,
  • Compares each pair of adjacent elements. Keep comparing one element to the one right next to it,
  • Swaps them if they are in the wrong order. If the element on the right is smaller, we swap the two positions.
  • Repeat the process until no swaps are required, implies the list is sorted.
 function swapElement(arr, firstIndex, secondIndex){
    var tmp = arr[firstIndex];
    arr[firstIndex] = arr[secondIndex];
    arr[secondIndex] = tmp;
}

function bubbleSort(arr){

    var len = arr.length,
        i, j, stop;

    for (i = 0; i < len; i++){
        for (j = 0, stop = len-i; j < stop; j++){
            if (arr[j] > arr[j+1]){
                swapElement(arr, j, j+1);
            }
        }
    }

    return arr;
}
console.log(bubbleSort([30, 3, 90, 150, 45, 63, 27, 18, 12, 999]));

Code: https://runkit.com/sanmak/javascript-algorithms-sort-a-list-using-bubble-sort

Code Explanation

  • We start with the first element, then compare it with the second. Here, it’s 30 and 3.
  • If the first is greater than the second, then we swap them, else no change. Since 30 > 3, therefore we need to swap. New array will looks like, [3, 30, 90, 150, 45, 63, 27, 18, 12, 999]
  • Now switch to the second element of the array. Compare 30 and 90
  • Compare it with the third element. And continue the process.

Step by step Explanation by w3resource:

bubble-sort

As it’s clear from the algorithm that we are looping the array 2 times, due to a check whether we need to swap the item with the one on the right or not and this leads to the order of complexity to O(N^2). An inefficient sorting implementation.

Learn the basics of bubble sort algorithm with Gayle Laakmann McDowell in a HackerRank series.

Any thoughts, let's discuss on twitter

Sharing this article is a great way to educate others like you just did.



If you’ve enjoyed this issue, do consider subscribing to my newsletter.


Subscribe to get more such interesting content !

Tech, Product, Money, Books, Life. Discover stuff, be inspired, and get ahead. Box Piper is on Twitter and Discord. Let's Connect!!

To read more such interesting topics, let's go Home

More Products from the maker of Box Piper:

Follow GitPiper Instagram account. GitPiper is the worlds biggest repository of programming and technology resources. There is nothing you can't find on GitPiper.

Follow SharkTankSeason.com. Dive into the riveting world of Shark Tank Seasons. Explore episodes, pitches, products, investment details, companies, seasons and stories of entrepreneurs seeking investment deals from sharks. Get inspired today!.


Scraper API

More Blogs from the house of Box Piper: