Bubble

Bubble Sort is a simple sorting algorithm that repeatedly steps through a list of elements, compares adjacent elements and swaps them if they are in the wrong order.

The algorithm gets its name from the way smaller elements "bubble" to the top of the list with each iteration.

pseudocode:

procedure bubbleSort(A : list of sortable items)
    n = length(A)
    swapped = true
    while swapped
        swapped = false
        for i = 0 to n-2
            if A[i] > A[i+1] then
                swap A[i] and A[i+1]
                swapped = true
            end if
        end for
        n = n - 1
    end while
end procedure

Here are the basic steps of the Bubble Sort algorithm:

  1. Starting at the beginning of the list, compare each pair of adjacent elements.

  2. If the elements are in the wrong order (e.g., the second element is smaller than the first), swap them.

  3. Continue iterating through the list until no more swaps are needed (i.e., the list is sorted).

The list is now sorted. Bubble Sort has a time complexity of O(n^2), making it relatively slow for large datasets.

However, it is easy to understand and implement, and can be useful for small datasets or as a starting point for more optimized sorting algorithms.

Implementation in JavaScript

function BubbleSort(arr) {
    let n = arr.length;
    let swapped = true;

    while (swapped) {
        swapped = false;
        for (let i = 0; i < n - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                let temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
                swapped = true;
            }
        }
        n--;
    }
    return arr;
}

console.log(BubbleSort([99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]));

Output

PS D:\Coding Playground> node playground2.js
[
    0,  1,  2,  4,  5, 6, 44, 63, 87, 99, 283
]

Last updated