by Sai gowtham

How to implement Bubble sort algorithm in JavaScript

Bubble sort algorithm is one of the slowest algorithms with O(n2) time complexity. In nearly sorted data bubble sort algorithm takes O(n) time.

If you don’t know about Big O notation and logarithms then please check out my previous tutorials.

How to implement bubble sort?

In bubble sort algorithm, we need to compare the adjacent elements.If the adjacent elements are in wrong order then we need to swap them until every element is sorted in correct order.

bubble sort algorithm visualization

Algorithm implementation

function bubbleSort(arr, length = arr.length) {
    while (length) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[ i ] > arr[i + 1]) {
                let temp = arr[ i ];
                arr[ i ] = arr[i + 1];
                arr[i + 1] = temp
            }
        }
        length--;
    }
    return arr;
}

console.log(bubbleSort([3,9,2,29,1]))

// output - >  [1, 2, 3, 9, 29]

In the above code, we are comparing the adjacent elements in the array if the first element is greater than the second element we swapped it.

Bubble sort implementation using JavaScript map method

function bubbleSort(arr) {
    arr.map(e1 => arr.map((e2, i) => {
        if (arr[ i ] > arr[i + 1]) {
            arr[ i ] = arr[i + 1];
            arr[i + 1] = e2;
        }
    }))
    return arr
}

The modified version using array destructuring.

function bubbleSort(arr) {
    arr.map(e1 => arr.map((e2, i) => {
        if (arr[ i ] > arr[i + 1]) { // comparing adjacent elements
           [arr[ i ],arr[i+1]]= [arr[i+1],arr[ i ]]  // swapping
        }
    }))
    return arr
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course