Sorting Algorithms : Selection Sort
Time Complexity :
Worst Case : O(n²)
It could be slightly better than “Bubble Sort” in case that you want to minimize the swaps.
How it works :
Contrary to Bubble Sort, this algorithm will start sorting the elements towards the beginning of the array instead of the end.
To accomplish that it needs to create a variable where it will be storing the lowest value and comparing with the rest of the elements.
If during the iteration finds a lower value, it will update our variable so when the iteration is done, the lowest value will swap with the first index of that iteration.
In order two swap the items let’s reuse the swap function that we created for the Bubble Sort Algorithm.
It will repeat the whole operation until the array is sorted.
Let’s visualize the algorithm:
Swap helper function :
For more info about how this function works, please check Bubble Sort.
Pseudocode :
// Store in a variable the index of the smallest value so far.// Iterate over the array comparing the elements with the smallest
value.// If a smaller value is found, replace the variable with the new
element.// Iterate until the end of the array and swap the lowest found
value.// If the "smaller" is not the value (index) you initially began
with, swap both elements (lowest element and initial index for
this iteration).// Repeat this operation with the next element until the array is
sorted.
Code :
Please, check here the explanation for other basic sorting algorithms :