Selection Sort

In this approach, the code implements selection sort by iterating through the array, finding the smallest element, and swapping it with the current element. Finally, it returns the sorted array.

Example: The example below shows Sorting Algorithms in JavaScript using Selection Sort.

JavaScript
function selectionSortFun(arr) {
    const 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;
            }
        }
        if (minIndex !== i) {
            [arr[i], arr[minIndex]] = 
                    [arr[minIndex], arr[i]];
        }
    }
    return arr;
}
const arr = [64, 34, 25, 12, 22, 11, 90];
console.log(selectionSortFun(arr)); 

Output
[
  11, 12, 22, 25,
  34, 64, 90
]

Time Complexity: O(n2)

Space Complexity: O(1)

Sorting Algorithms in JavaScript

Given an unsorted array, our task is to Sort the Array in JavaScript. We will sort the array using different sorting algorithms including Bubble Sort, Selection Sort, Insertion Sort and Merge Sort.

Example:

Input: [64, 34, 25, 12, 22, 11, 90]
Output: [11, 12, 22, 25, 34, 64, 90]

These are the following Sorting Algorithms:

Table of Content

  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Merge Sort

Similar Reads

Bubble Sort

In this approach, The Bubble Sort in JavaScript is used by iterating through the array, comparing adjacent elements, and swapping them if they are in the wrong order. This process repeats until the array is fully sorted, with the sorted array returned at the end....

Selection Sort

In this approach, the code implements selection sort by iterating through the array, finding the smallest element, and swapping it with the current element. Finally, it returns the sorted array....

Insertion Sort

In this approach, utilize the Insertion Sort algorithm to arrange elements in ascending order by repeatedly placing each element in its correct position among the already sorted elements. Finally, the sorted array is returned....

Merge Sort

In this approach, the code implements the merge sort algorithm recursively. It divides the array into halves until each part contains only one element, then merges them in sorted order. By repeatedly merging sorted subarrays, it constructs the final sorted array. This method ensures efficient sorting....