Javascript Functions - Selection Sort algorithm

Subscribe to my newsletter and never miss my upcoming articles

One more example of functions in javascript. This time I used Selection sort algorithm as an exampe.

Selection sort is the second simplest sorting algorithm. Today, we will learn how it works.

Selection sort sees the array as two parts, the unsorted part an sorted part. in this example we have the sorted part on the left on the array and the unsorted on the right of the array. at starting the sorted part will be empty and and the unsorted will be the whole array.

This algorithm looks for the smallest element in the unsorted array and once it finds it, it is swapped with leftmost element, so that element will be part of the sorted array. After that it moves the starting of the unsorted array to the right by one element.

Note: normally this algorithm is used to handle small amounts of data or for teaching purposes.

Please consider the following unsorted array

Positions: 1st 2nd 3rd 4rd 5th 6th 7th 8th

Values: 40, 20, 30, 10, 60, 15, 0, 1

Notice that in 1st position of the array we 40. What we need to do now is scan the whole array for the smallest value (in this case is 0), once we found it, we will swap it with 40.

Now the array has: 0, 20, 30, 10, 60, 15, 40, 1

Now for the 2nd position we have 20. Again we will need to scan array for the smallest value (in this case is 1) in the array Once we find it we swap with 20.

Now the array has: 0, 1, 30, 10, 60, 15, 40, 20

Now for the 3rd position we have 30. Again we will need to scan array for the smallest value (in this case is 10) in the array Once we find it we swap with the value in 3rd position.

Now the array has: 0, 1, 10, 30, 60, 15, 40, 20

Now for the 4th position we have 30. Again we will need to scan array for the smallest value (in this case is 15) in the array Once we find it we swap values with the value in the 4th position.

Now the array has: 0, 1, 10, 15, 60, 30, 40, 20

Now for the 5th position we have 60. Again we will need to scan array for the smallest value (in this case is 20) in the array Once we find it we swap the value in position 5th.

Now the array has: 0, 1, 10, 15, 20, 30, 40, 60

Now for the 6th position we have 30. Again we will need to scan array for the smallest value (in this case is 30) in the array Once we find it we swap with the value in position 6th. (swap doe snot occur here as30 is the smallest)

Now the array has: 0, 1, 10, 15, 20, 30, 40, 60

Sorted array: 0, 1, 10, 15, 20, 30, 40, 60

Please see live example here:

(blue circles: move mouse over to see old values)

Thank you for reading this article, hope you enjoy it.

Let's Connect

Next Article will be: Insertion sort

No Comments Yet