Skip to content

Instantly share code, notes, and snippets.

@msaxena25
Last active March 27, 2018 10:33
Show Gist options
  • Save msaxena25/ebc00535b71b58ffb9d2041631d413a3 to your computer and use it in GitHub Desktop.
Save msaxena25/ebc00535b71b58ffb9d2041631d413a3 to your computer and use it in GitHub Desktop.
Selection Sort Algorithm in JavaScript
This algorithm will first find the smallest element in the array and swap it with the element in the first position,
then it will find the second smallest element and swap it with the element in the second position,
and it will keep on doing this until the entire array is sorted.
// Method to find Minimum Value and Minimum Index
function findMinIndex(arr, startIndex) {
var minIndex = startIndex;
var minValue = arr[startIndex];
for (var i = startIndex + 1; i < arr.length; i++) {
if (arr[i] < minValue) {
minValue = arr[i];
minIndex = i;
}
}
return minIndex;
}
// Swap element
function swap(arr, firstIndex, secondIndex) {
var temp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = temp;
}
function sortArray(arr) {
let length = arr.length;
for (var i = 0; i < length; i++) {
var minIndex = findMinIndex(arr, i);
swap(arr, i, minIndex);
}
console.log(arr);
}
var arr = [12, 23, 1, 4, 16];
sortArray(arr); // call function
Output : [1, 4, 12, 16, 23]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment