Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences…

Member-only story

Sorting Algorithms: Selection Sort

Akiko Green
Nerd For Tech
Published in
3 min readFeb 14, 2023

--

image of 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…

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Akiko Green
Akiko Green

Written by Akiko Green

Software Engineer, Novice Blogger, Indoor Climber and Dog sitting expert 🥰

No responses yet