Algorithm: Selection Sort

Selection Sort is a simple sorting algorithm. It’s an in-place comparison-based algorithm in which the list is dived into 2 parts, the sorted part at the left end and the unsorted part at the right end. Placing the smallest element in the array first in the sequence and gradually increase to the largest element at the end of the sequence.

Let’s say we have an array of random numbers, and you need them to sort them from smallest to largest:

  1. Select the smallest element in the array
  2. Bring it to the starting position
  3. And change the counter for unsorted array by 1

In our example we are coding in JavaScript. First let’s make a function named selectionSort. Our function is taking in an argument of “arr” which is an array of unsorted numbers. And we using a for loop to iterate through the array.

function selectionSort(arr) {  for(let i = 0; i < arr.length - 1; i++) {  }};

Let’s break down what we are doing here:

  • Initialization, we are setting “i” to equal 0.
  • Condition, we are saying that “i” is less than the length of our array that we are looping through. The “- 1” is to prevent fencepost errors, because JavaScript arrays are 0-based. Meaning the index value of the first element in the array is “0” and the index value of the second element is “1”, the third element’s index value is “2”, and so on.
  • Iteration, we are incrementing our “i” value by 1.
function selectionSort(arr) {  for (let i = 0; i < arr.length - 1; i++) {    let jMin = i      for (let j = i + 1; j < arr.length; j++) {        if (arr[j] < arr[jMin]) {          jMin = j        }     }  }};

In our 1st for loop block, we are declaring “jMin” to be “i”. We could think “jMin” to be the starting point. Then we for looping again, this time:

  • Declaring “j” to be “i” plus 1
  • “j” is less than the array length
  • Incrementing “j” by 1

Inside our 2nd for loop block, we are using a if statement to check if the element to be minimum. If so then that’s our new minimum, redeclaring our “jMin” variable to be “j” now.

Going back to our 1st for loop block, we are simply swamping our old minimum to the new minimum.

function selectionSort(arr) {  for (let i = 0; i < arr.length - 1; i++) {    let jMin = i      for (let j = i + 1; j < arr.length; j++) {        if (arr[j] < arr[jMin]) {          jMin = j        }      }    if (jMin != i) {      [arr[i], arr[jMin]] = [arr[jMin], arr[i]]    }  }};

And that’s pretty much it, it may look confusing at first but if you break it down it makes sense. Thank you for reading!

I’m a Software Engineer who is always learning something new!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store