JSFiddle - React, Tailwind, and code Playground
by stanney
JavaScript
function swap(list, i, j) {
var tmp = list[i];
list[i] = list[j];
list[j] = tmp;
}
function ascending(a, b) {return a - b;}
function selectedIdx(list, from, to, compare) {
var selected = from;
for(var i = from + 1; i < to; i++) {
if(compare(list[i], list[selected]) < 0) {
selected = i;
}
}
return selected;
}
function selectionSort(list, compare) {
for(var i = 0; i < list.length; i++) {
var selected = selectedIdx(list, i, list.length, compare);
if(selected !== i) { swap(list, i, selected); }
}
}
var list = [10, 9, 1, 2, 5, 3, 8, 7];
selectionSort(list, ascending);
console.log(list);