Created
January 29, 2019 14:03
-
-
Save bluurn/24cc604f4e0b02780a376c8cfad6771f to your computer and use it in GitHub Desktop.
JS: Selection Sort Implementation
This file contains 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
var swap = function(array, firstIndex, secondIndex) { | |
var temp = array[firstIndex]; | |
array[firstIndex] = array[secondIndex]; | |
array[secondIndex] = temp; | |
}; | |
var indexOfMinimum = function(array, startIndex) { | |
var minValue = array[startIndex]; | |
var minIndex = startIndex; | |
for(var i = minIndex + 1; i < array.length; i++) { | |
if(array[i] < minValue) { | |
minIndex = i; | |
minValue = array[i]; | |
} | |
} | |
return minIndex; | |
}; | |
var selectionSort = function(array) { | |
var minIdx; | |
for(var i = 0; i < array.length; i++) { | |
minIdx = indexOfMinimum(array, i); | |
swap(array, i, minIdx); | |
} | |
}; | |
var array = [22, 11, 99, 88, 9, 7, 42]; | |
selectionSort(array); | |
println("Array after sorting: " + array); | |
Program.assertEqual(array, [7, 9, 11, 22, 42, 88, 99]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment