The task is to implement a selection sort that sorts an integer array in ascending order.
The boilerplate code:
function selectionSort(arr) {
// your code here
}
The array is divided into 2 parts: The sorted part and the unsorted. For each position i, it assumes that arr[i] is the smallest of the unsorted part.
let minIndex = i
The rest of the array is scanned to find the smallest element
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
If the element found is smaller than arr[i], it swaps the value of arr[i] with the element.
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
It continues until the array is fully sorted. The final code is
function selectionSort(arr) {
// your code here
for(let i = 0; i <arr.length - 1; i++) {
let minIndex = i;
for(let j = i +1; j < arr.length; j++) {
if(arr[j] < arr[minIndex]) {
minIndex = j
}
}
if(minIndex !== 1) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]
}
}
}
That's all folks!
Top comments (0)