Exploring Three Common Sorting Algorithms with JavaScript

Sorting algorithms are fundamental in computer science and are used to arrange elements in a specific order. In this blog post, we'll explore three common sorting algorithms implemented in JavaScript: Bubble Sort, Insertion Sort, and Merge Sort. Let's dive in!

Exploring Three Common Sorting Algorithms with JavaScript


Bubble Sort

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


function bubbleSort(arr) {
    const n = arr.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap elements
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}
const array = [64, 34, 25, 12, 22, 11, 90];
console.log("Bubble Sort:", bubbleSort(array));

Insertion Sort

Insertion Sort is another simple sorting algorithm that builds the final sorted array one element at a time by repeatedly shifting larger elements to the right.


function insertionSort(arr) {
    const n = arr.length;
    for (let i = 1; i < n; i++) {
        let key = arr[i];
        let j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
    return arr;
}
const array = [64, 34, 25, 12, 22, 11, 90];
console.log("Insertion Sort:", insertionSort(array));

Merge Sort

Merge Sort is a divide-and-conquer algorithm that divides the input array into smaller sub-arrays, sorts them independently, and then merges them to produce the final sorted array.


function mergeSort(arr) {
    if (arr.length <= 1) {
        return arr;
    }
    const mid = Math.floor(arr.length / 2);
    const left = mergeSort(arr.slice(0, mid));
    const right = mergeSort(arr.slice(mid));
    return merge(left, right);
}

function merge(left, right) {
    let result = [];
    let i = 0;
    let j = 0;
    while (i < left.length && j < right.length) {
        if (left[i] < right[j]) {
            result.push(left[i]);
            i++;
        } else {
            result.push(right[j]);
            j++;
        }
    }
    return result.concat(left.slice(i)).concat(right.slice(j));
}

const array = [64, 34, 25, 12, 22, 11, 90];
console.log("Merge Sort:", mergeSort(array));

These are just a few examples of the many sorting algorithms out there. Each algorithm has its strengths and weaknesses, and the choice of algorithm depends on factors such as input size, data distribution, and performance requirements.

Experiment with different sorting algorithms and see how they perform on different datasets. Understanding sorting algorithms is not only essential for solving programming challenges but also for building efficient and scalable applications.

Previous Post Next Post

Contact Form