A Beginner's Guide to Selection Sort Algorithm with Javascript Example
Selection sort is a simple sorting algorithm that works by repeatedly selecting the smallest element from an unsorted list and placing it at the end of a sorted list. It does this by using two nested loops. The outer loop keeps track of the current position in the sorted portion of the array, and the inner loop finds the next smallest element in the unsorted portion of the array.
The algorithm starts by assuming that the first element of the array is the smallest. It then compares this element to every other element in the array. If it finds a smaller element, it updates the index of the smallest element and continues this process until the end of the array is reached.
Once the smallest element is found, it is swapped with the first element of the array. This moves the smallest element to the beginning of the sorted portion of the array.
The outer loop then increments by 1, and the process repeats, this time considering the second element as the starting point of the unsorted portion of the array. The inner loop will again compare every other element to this element and find the next smallest element. This process continues until the outer loop reaches the end of the array.
It is to be noted that the time complexity of this algorithm is O(n^2) , which is not efficient for large datasets. It is a simple algorithm to learn and understand but not recommended for production use.
Here is an example of selection sort implemented in JavaScript:
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let minIndex = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
return arr;
}
console.log(selectionSort([5, 3, 6, 2, 10]));
This implementation loops through the array, each time selecting the next smallest element and swapping it with the current element in the sorted portion of the array. The outer loop keeps track of the current position in the sorted portion of the array, and the inner loop finds the next smallest element in the unsorted portion of the array.
It can be observed that the selection sort algorithm loops through the array twice, once to find the smallest element, and once to place it in the correct position. The time complexity of this algorithm is O(n^2) and it is not recommended for large datasets, but it is a simple algorithm to learn and understand.
Comments
Post a Comment