Created
March 6, 2020 11:49
-
-
Save MostafaEzzelden/87db826a197ee4833e43d299ca4168db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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