Implement Bubble Sort In JavaScript

Bubble sort is one of the simplest sorting algorithms for an array. It is an iterative sorting algorithm that repeatedly swaps adjacent elements if they are in the wrong order. It is named bubble sort because smaller or larger elements 'bubble up' to the top or bottom of the array, respectively. The code example in this article demonstrates how to implement a bubble sort in JavaScript to sort an array.

Bubble Sort Implementation in JavaScript

The basic idea behind bubble sort is to iterate through the array, comparing adjacent elements and swapping them if they are in the wrong order. The algorithm continues until no swaps are needed, indicating that the array is sorted. Let's take a look at the sample code for bubble sort in JavaScript,

function bubbleSort(arr) {
    let n = arr.length;
    // loop through the array 
    for (let i = 0; i < n; i++) {
        // last i elements are already in place 
        for (let j = 0; j < n - i - 1; j++) {
            // swap adjacent elements if they are in the wrong order 
            if (arr[j] > arr[j + 1]) {
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}
// sample usage 
let arr = [64, 34, 25, 12, 22, 11, 90];
console.log(bubbleSort(arr));
// [11, 12, 22, 25, 34, 64, 90]

In the above code, we define a function called bubbleSort, which takes an array as input and returns the sorted array. The outer loop iterates through the entire array, and the inner loop iterates through the array until the last ith elements, as they are already in place. The if condition checks whether the adjacent elements are in the wrong order and swaps them if necessary.

In the worst case, the time complexity of bubble sort is O(n^2), where n is the number of elements in the array. This makes bubble sort inefficient for large arrays. However, bubble sort is easy to understand and implement and can be used for educational purposes.

Conclusion

In this article, we have seen how to implement bubble sort in JavaScript. Bubble sort is a simple sorting algorithm that can be used for educational purposes or sorting small arrays. However, it is unsuitable for large arrays as its time complexity is O(n^2), making it inefficient. Other sorting algorithms like quicksort and mergesort are more efficient for sorting large arrays.