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.
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