Skip to content

Instantly share code, notes, and snippets.

@MostafaEzzelden
Created March 6, 2020 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MostafaEzzelden/87db826a197ee4833e43d299ca4168db to your computer and use it in GitHub Desktop.
Save MostafaEzzelden/87db826a197ee4833e43d299ca4168db to your computer and use it in GitHub Desktop.
/*
SELECTION SORT
*** Description
Iterate over array and grow a sorted array behind current element.
For each position, find the smallest element in unsorted subarray starting at that position,
and swap elements so that smallest element is at the beginning of unsorted subarray.
*/
const selectionSort = function(array, comparator) {
comparator = comparator || defaultComparator;
array.forEach(function(element, index) {
// for each position, find index of minimum value in subarray starting at that positions
var minValue = element;
var minIndex = index;
for (var i = index; i < array.length; i++) {
if (comparator(array[i], minValue) < 0) {
minValue = array[i];
minIndex = i;
}
}
// swap values at min index and current position
swap(array, index, minIndex);
});
};
function swap(array, i1, i2) {
let temp = array[i1];
array[i1] = array[i2];
array[i2] = temp;
}
function defaultComparator(a, b) {
if (a < b) return -1; // a comes first
else if (a > b) return 1; // b comes first
return 0;
};
export default selectionSort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment