Author -  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 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY