The selection sort algorithm in JavaScript involves iteratively finding the minimum element from the unsorted portion of an array and swapping it with the first unsorted element. This process is repeated until the entire array is sorted in ascending order.
The algorithm’s implementation includes nested loops for comparing and swapping elements, resulting in a sorted array at the end.
Here’s a step-by-step explanation of the selection sort algorithm in JavaScript:
- Start with an unsorted array of elements.
- Iterate through the array from the first element to the second-to-last element. This will be done using a variable
i
that represents the current index. - Assume the element at index
i
is the minimum value. Assigni
to a variableminIndex
. - Start another iteration from the next element after
i
to the last element of the array. This will be done using a variablej
that represents the current index. - Compare the element at index
j
with the element at indexminIndex
. If the element at indexj
is smaller than the element at indexminIndex
, updateminIndex
toj
. - After the inner loop completes, swap the element at index
i
with the element at indexminIndex
. This places the minimum value in its correct position at the beginning of the unsorted part of the array. - Repeat steps 3 to 6 for each subsequent index
i
, until the second-to-last element of the array. - Once the outer loop completes, the array is sorted in ascending order.
Selection sort JavaScript example
Simple example code implementation of the selection sort algorithm in JavaScript:
function selectionSort(arr) {
const len = arr.length;
for (let i = 0; i < len - 1; i++) {
let minIndex = i;
// Find the index of the minimum element in the unsorted part of the array
for (let j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the minimum element with the first element in the unsorted part of the array
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
// Example usage:
const array = [64, 25, 12, 22, 11];
console.log(selectionSort(array));
Output:
You can test the code with different arrays by changing the values in the array
variable and calling selectionSort(array)
.
The time complexity of the selection sort algorithm in JavaScript is O(n^2), where n is the number of elements in the array.
Comment if you have any doubts or suggestions on this JS sorting algorithm topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version