selection_sort
selection_sort
Implementation
Selection sort works by splitting the array into two parts: a
sorted array and an unsorted array. If we are given an array Step-by-step process for
of the numbers 5, 1, 6, 2, 4, and 3 and we wanted to sort it selection sort
using selection sort, our pseudocode might look something
like this:
5 1 6 2 4 3
repeat for the amount of elements in the array
find the smallest unsorted value
swap that value with the first unsorted value
Sorted Arrays
Unlike bubble sort, it is not necessary to keep a counter of how many swaps were made. To optimize this algo-
rithm, it might seem like a good idea to check if the entire array is sorted after every successful swap to avoid
what happened in the last two steps of the pseudocode above. This process too, comes at a cost, that is even
more comparisons that we have to make. We are guaranteed though, that no matter the order of the original ar-
ray, a sorted array can be formed after n-1 swaps, which is significantly fewer than that of bubble sort. In selection
sort, in the worst case scenario, n2 comparions and n-1 swaps are made. Unfortunately, that’s also the case in the
best-case scenario!