Member-only story
Sorting Algorithms: Selection Sort
Today we will be discussing Selection Sort! What this algorithm does, is find the smallest element in an unsorted array, and place it at the front . Although, that may sound like it would be a fast way to sort an array, selection sort proves you wrong.
The Pseudocode
- Write a function called selectionSort that takes an array as an argument.
- iterate through the array with a variable i. Store the first element as the smallest value seen.
- iterate through the array again with a variable of j at the next index of i.
- if the our value at arr[j] has a smaller value than our lowest variable found, we can assign that value as the lowest.
- if our value at the index of i is not the smallest value encountered. Start the swapping sequence.
- Repeat the same steps with the next element until the array is sorted.
The Code
function selectionSort(arr){
console.log(arr, 'original')
for(var i = 0; i < arr.length; i ++){
var lowest = i
for(var j = i + 1; j < arr.length; j++){
if(arr[j] < arr[lowest]){
lowest = j
}
}
// if our current i is not the lowest value, start switching
if(i !== lowest){
//create switch here…