Bubble Sort Algorithm in JavaScript

Here we will learn a simple sorting algorithm that is bubble sort. It is the simplest of all the sorting algorithms.
The bubble sort algorithm compares every two adjacent items and swaps them if the first one is bigger than the second one. It has this name because the items tend to move up into the correct order, like bubbles rising to the surface.

Bubble Sort Algorithm in JavaScript

function bubbleSort(array) {
    const length = array.length;
    for (let i = 0; i < length; i++) {
        for (let j = 0; j < length - 1; j++) {
            if (array[j] > array[j + 1]) {
                swap(array, j, j + 1);
            }
        }
    }
    return array;
}

function swap(array, a, b) {
    const temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}

Using Bubble Sort Algorithm

const array1 = [2, 1, 3, 7, 6, 5];
const array2 = bubbleSort(array1);
console.log(array2);

Output

[1, 2, 3, 5, 6, 7]

Demo


Comments

Post a Comment