Bubble sort algorithm in js

Bubble sort is the simplest, comparison-based sorting algorithm. It repeatedly steps through the list to compare and swap adjacent elements if they are in the wrong order. The pass-through process continues until the list comes out sorted. The name "Bubble Sort" was given to this algorithm because with every pass, the smaller elements in the list seem to "bubble" to the top of the list from the array. Steps of Bubble Sort: Compare the first two elements in the array. If the first is greater than the second, then swap. Now, move to the next pair of elements in the array and repeat the comparison and swapping process until it reaches the end. Pass through the array again: The greatest element will move to the end of the array after one pass is done. Do this for the remaining array until it's sorted. Check if sorted: Keep repeating until no swaps are needed, meaning it's sorted.

Bubble Sort Program in JavaScript

Here’s a program to sort the array const numbers = [2, 4, 1, 67, 34, 5, 90, 1, 5, 9]; using Bubble Sort:

function sortFunction(arr) { // using bubble sort
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = 
                            [arr[j + 1], arr[j]];
            }
        }
    }
    return arr;
}
const numbers = [64, 34, 25, 12, 22, 11, 90];
console.log(sortFunction(numbers)); 

Comments

Popular posts from this blog

Closures in JS