Being Selective

Daniel C Reyes
3 min readJan 31, 2021

--

Selective Sort in JavaScript

As I continue my journey into data structures and algorithms the realization that sorting algorithms are vital to becoming a strong programmer becomes more clear. A sorting algorithm arranges the elements in a collection of data in the right order. It is often useful while programming, as it is useful in locating elements and sorting elements. One of the most useful sorting algorithms used is the Selection Sort. The goal of the selection sort algorithm is to select the first smallest element in your array and then swap it to the first position.

Selection Sort, but dogs!

How Selection Sort Works

Selection sort is a comparison sorting algorithm, where it has to iterate through a given array or data structure and compare each number with the goal of computing a minimum number so that it can swap it with the number found at the beginning of the array.

Steps of Selection Sort

  • Store the first element index as the smallest value, you’ve seen so far.
  • Iterate through the array and try to find a smaller value compared to the first element.
  • When and if a smaller number is found, designate that number index to be the new minimum.
  • In the case of the current minimum not being equal to what we initially began with, swap the 2 values.
  • Finally, repeat this process with the next element until the whole array is sorted. A big reason why we select the next element is to avoid the redundancy of going through the already sorted elements.

Selection Sort: THE CODE!

const selectionSort = (array) => {
// start looping at the beginning of the array.
for(let i = 0; i < array.length; i++) {
// select the element's index at the beginning as the current minimum number.
let min = i;
// loop thourgh the array from the next element of the array
// this will help us in checking only against the unsorted
// elements, as we know the elements before it are already sorted.

for(let j = i + 1; j < array.length; j++){
// check if the current element is less than the initial minimum
// and assign the minimum to be the current element if that's the case.
if(array[j] < array[min]) min = j;
}
// at this stage, we are checking if the new minimum index number
// is not equal to the one we begin with.
// analyze the code, and you will notice that we are still in the outer loop where i is still 0.

// which was our initial minimum number value, so after
// looping through the array again with the inner loop and
// we found another new minimun number, we are now swapping those two values.

// after that, we repeat the same process until the array is sorted.
i !== min && swap(array, i, min);
}
return array;
};

--

--

Daniel C Reyes
Daniel C Reyes

Written by Daniel C Reyes

Full-Stack Software Engineer / New York City / www.danielcreyes.dev

No responses yet