Data Structure: Selection Sort

What is the Selection sort?

The selection sort method is a useful method. This method will take an array of unsorted numbers and sort them from small to large depending on your condition. The way it is able to perform this method is by finding the minimum element Index.

How does it work

Since we are storing the indices of each element we need to create a variable.

let min;

Once the variable is established we need to iterate through the array.

for(let i = 0; i < array.length - 1; i++){

Notice how the loop is formed with array.length — 1. This is because once we sort a set of arrays we will decrease the number of elements in that array. Upon setting up the first set of iteration, the variable min needs a value. We can set min to I since the value is zero.

for(let i = 0; i < array.length - 1; i++){
min = i

The second iteration starts at the first index.

for(let j = i + 1; j < array.length; j++){

. Furthermore inside of the loop, a conditional is needed to be added. If the first index is less than the one before. We set the variable to the index.

if(array[j] < array[min]) min = j

Each value that has the least value compared to the index before it will be stored by index.

Just to make sure our loop goes as planned. We break out of our loop to add another conditional that stops the current index and variable to equal to another.

if(i !== min){

If the condition evaluates to true we will proceed to swap the two values and return the array in the correct order.

if(i !== min){
let temp = array[i]
array[i] = array[min]
array[min] = temp
}

Here’s a full view of the algorithm.

function selectionSort(array) {
let min;
for(let i = 0; i < array.length - 1; i++){
min = i
for(let j = i + 1; j < array.length; j++){
if(array[j] < array[min]) min = j
}
if(i !== min){
let temp = array[i]
array[i] = array[min]
array[min] = temp
}
}
return array
}

Let's talk about Time Complexity

The time complexity is considered to be O(n2). Looping twice through an array to return our ordered elements. Leave a comment below for any question

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Map!! Filter!! Reduce !!

How to Create a Staging Environment in create-react-app

File Upload — Express, MongoDB, Multer & S3

day 13 of my #1000daysofcoding

Video Chat app using Gatsby and twilio-3

The Ultimate Guide to Infinite Scrolling in Angular 11

JS-PostIt@01 —  ES5 vs ES6

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
Woodelin florveus

Woodelin florveus

More from Medium

How to Hire Java Developers: The Time is Now

How to Hire Java Developers

An Overview Of Optimizer In Oracle| Interview Q&A

Indexes In Databases

CS373 Spring 2022: Vibhuti Sharma