23 lines
588 B
JavaScript
23 lines
588 B
JavaScript
// 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
|
|
}
|