Algorithms: Implement Selection Sort

This commit is contained in:
Manish 2023-08-22 10:52:15 +10:00
parent e693c0078c
commit b7be24f4c6

View File

@ -0,0 +1,22 @@
// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-selection-sort
function selectionSort(array) {
// Only change code below this line
const swap = (array, indexA, indexB) => {
const temp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = temp;
};
for (let i = 0; i < array.length; i++) {
let minIndex = i;
for (let j = i; j < array.length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
swap(array, i, minIndex);
}
}
return array;
// Only change code above this line
}