This is a naive attempt of writing a recursive and non-recursive versions for SelectionSort()
. My goal is mainly to present an elegant, easy-to-understand, idiomatic code, and therefore, performance is a distant priority. Please comment away!
// Find the index at which the minimum value
// exists inside the Array
function findMinIndex(a){
return a.reduce((iMin, x, i, arr) => x < arr[iMin]? i : iMin, 0);
}
// Remove the minimum value from the array
// Return the value removed
function removeMin(a){
idx = findMinIndex(a);
minVal = a[idx]; // for [1, -5, 3], minVal = -5
a.splice(idx, 1); // [1, -5, 3] -> [1, 3]
return minVal;
}
// Selection sort, in recursive mode
// As the name suggests, we select and 'splice' it
// away from the array, and recursively
// concatenate it to get the final result
function selectRecursive(a) {
if (!a.length) return []; // terminating case
minVal = removeMin(a); // remove the smallest
console.log(v, a);
return [minVal].concat(selectRecursive(a));
}
var myl = [1, 2, 3, 99, 22, 55, 5];
selectRecursive(myl);
OUTPUT
1 [ 2, 3, 99, 22, 55, 5 ]
2 [ 3, 99, 22, 55, 5 ]
3 [ 99, 22, 55, 5 ]
5 [ 99, 22, 55 ]
22 [ 99, 55 ]
55 [ 99 ]
99 []
[ 1, 2, 3, 5, 22, 55, 99 ]
In addition, a non-recursive (less intuitive in my opinion) version of SelectionSort (using push
, slice
, splice
and the spread
operator) is presented below.
function selectionSort(a) {
var length = a.length;
for (var i = 0; i < length; i++) {
a.push( // select and append at the end
...a.splice(
findMinIndex( // get min in a sliced 'a'
a.slice(0, length - i)), 1)
);
}
return a;
}