HomeAbout MeContact

javascript algorithms - Bubble sort Explained using Javascript .

By Gopal Baskota
Published in JavaScript
January 10, 2021
1 min read

Bubble sort is the most common and simplest of all the sorting algorithms. In bubble sort, two elements of an array are compared and then swapped accordingly.

At the end of the first pass, the largest element is shifted or bubbled to the end of the array. This continues until the whole array is sorted.

Let’s understand with the help of an example.

[8, 2, 1, 3, 9] -> The sorting starts from the first index, compares the first to elements. [2, 8, 1, 3, 9] -> Since 8 > 2, they are swaped. Next, 8 is compared with next element i.e. 1. [2, 1, 8, 3, 9] -> 8 > 1, they are swaped. Next, 8 is compared with the next element i.e. 3. [2, 1, 3, 8, 9] -> 8 > 3, they are swaped. Next, 8 is compared with the next element i.e. 9. [2, 1, 3, 8, 9] -> Now, as the last two elements are already in order, the algorithm moves to the next pass.

The next pass will again start from the first element and this will continue until the sorting is done.

Following is the implementation of bubble sort using JavaScript.

let arr = [8, 2, 1, 3, 9]

let l = arr.length

for (let i = 0; i < l; i++) {
    for (let j = 0; j < l; j++) {
            if (arr[j] > arr[j + 1]) {
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
}

console.log(arr) //[1, 2, 3, 8, 9]

So in bubble sort implementation, two for loops are used and, in the nested for loop, swapping is performed. The average time complexity of bubble sort is O(n^2) and space complexity is O(1).


Tags

bubblesortjavascriptalgorithm
Previous Article
Big O notation In Javascript

Gopal Baskota

Full stack Web Developer

Topics

JavaScript
NodeJs
React Js

Related Posts

javascript algorithms - Insertion sort Explained using Javascript .
January 11, 2021
1 min
© 2021, All Rights Reserved.

Quick Links

Advertise with usAbout UsContact Us

Social Media