DEV Community

Cover image for Sorting Algorithms in JavaScript Bubble Sort, Insertion Sort, Selection Sort & Merge Sort.
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

1

Sorting Algorithms in JavaScript Bubble Sort, Insertion Sort, Selection Sort & Merge Sort.

Sorting is a fundamental concept in computer science, and different sorting algorithms have their own use cases, efficiency, and logic. In this article, we will cover four important sorting algorithms in JavaScript:

  1. Bubble Sort
  2. Insertion Sort
  3. Selection Sort
  4. Merge Sort

1. Bubble Sort
Bubble Sort repeatedly swaps adjacent elements if they are in the wrong order.

function bubbleSort(arr) {
    let len = arr.length;
    for (let i = 0; i < len - 1; i++) {
        for (let j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; // Swap
            }
        }
    }
    return arr;
}
console.log(bubbleSort([5, 2, 9, 1, 5, 6]));

Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n²)
1. Bubble Sort Visualization

Image description

2. Insertion Sort
Insertion Sort builds the sorted array one item at a time by shifting elements.

function insertionSort(arr) {
    let len = arr.length;
    for (let i = 1; i < len; 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;
}
console.log(insertionSort([5, 3, 8, 4, 2]));
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n²) (worst case), O(n) (best case when array is already sorted).

2. Insertion Sort Visualization

Image description


3. Selection Sort
Selection Sort repeatedly finds the smallest element and swaps it with the correct position.

function selectionSort(arr) {
    let len = arr.length;
    for (let i = 0; i < len - 1; i++) {
        let minIndex = i;
        for (let j = i + 1; j < len; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
    return arr;
}
console.log(selectionSort([29, 10, 14, 37, 13]));
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n²)

3. Selection Sort Visualization

Image description

4. Merge Sort
Merge Sort is a divide-and-conquer algorithm that splits the array into halves and merges them after sorting.

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 sortedArray = [];
    while (left.length && right.length) {
        if (left[0] < right[0]) {
            sortedArray.push(left.shift());
        } else {
            sortedArray.push(right.shift());
        }
    }
    return [...sortedArray, ...left, ...right];
}
console.log(mergeSort([38, 27, 43, 3, 9, 82, 10]));
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n log n).

Another Merge Sort Example (Manual Merging)
Here’s another example that manually merges two sorted arrays into one:

let data1 = [3, 7, 12, 34, 56, 90];
let data2 = [4, 9, 25, 45];
let data3 = [];

let d1 = 0, d2 = 0, d3 = 0;

while (d1 < data1.length && d2 < data2.length) {
    if (data1[d1] < data2[d2]) {
        data3[d3] = data1[d1];
        d1++;
    } else {
        data3[d3] = data2[d2];
        d2++;
    }
    d3++;
}

while (d1 < data1.length) {
    data3[d3] = data1[d1];
    d1++;
    d3++;
}

console.log("Final Merged Array:", data3);
Enter fullscreen mode Exit fullscreen mode

4. Merge Sort Visualization

Image description

Conclusion
Sorting algorithms play a vital role in data manipulation and optimization. While Bubble Sort, Insertion Sort, and Selection Sort are simple but inefficient for large datasets, Merge Sort offers a more optimized solution with O(n log n) complexity.

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay