Selection Sort
Selection sort uses nested loops as you might expect but the management of them is a little more complex than bubble sort.
As it runs, selection sort places the lowest element in the array in the correct (leftmost) location of the array on each iteration of the outer loop. As opposed to bubble sort which focuses on “bubbling” up the largest element to the rightmost array location per iteration.
Pseudo code:
Outer loop iterates over all elements with index
Set a
min_index
variable to hold the value ofi
inner loop compares all elements against
arr[i]
starting from indexj = i + 1
looking for the lower of the two- if
arr[j] < arr[i]
set themin_idex
variable to capture the index of the lower value
- if
We now have the index of the lowest number in that pass
swap the values
When all loops are run, print out results
So let’s look at this in C and then we’ll break it down as I found this tricky to get my head around:
#include <stdio.h>
int main(void){
int arr[]={5,1,9,2,7,6};
int min_index = 0;
int temp = 0;
int length = sizeof(arr) / sizeof(int);
for(int i = 0; i < length - 1; i++){
min_index = i;
for(int j = i + 1; j < length; j++){
if(arr[j] < arr[min_index]){
min_index = j;
}
}
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
for(int i = 0; i < length; i++){
printf("%d\n", arr[i]);
}
return 0;
}
So the first part is just setting things up.
#include <stdio.h>
int main(void){
int arr[]={5,1,9,2,7,6};
int min_index = 0;
int temp = 0;
int length = sizeof(arr) / sizeof(int);
Everything truly interesting happens in the loops. Note the inner loop will always start one index ahead of i
(this is why j = i + 1) and will compare all numbers from index j
to the end of the array against arr[min_index]
.
for(int i = 0; i < length - 1; i++){
min_index= i;
for(int j = i + 1; j < length; j++){
if(arr[j] < arr[min_index]){
min_index = j;
}
}
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
Walking through, here’s how the loops works:
for(int i = 0; i < length - 1; i++){
Our outer loop declaration, controlled by i
is the first thing to note. We iterate length - 1
times. Why?
As mentioned above, our inner loop controlled by j
is always looking one index ahead of i
, so we don’t want to run out of bounds of the array, which, if you don’t know C, it won’t stop you doing and only leads to bad things. So we run the loop length - 1
times.
Then we set this min_index
variable to be i
min_index = i;
Why?
We need something to check against! We’re effectively initialising min_index
with the value of i
. This is fine as we’re about to loop over the rest of the array and check to see if it truly is the index where the smallest of the remaining numbers lives.
There’s a detail that may not be immediately obvious about selection sort and that is the lowest value will be in the correct position after each iteration of the outer loop. When the outer loop increments to i = 1, we can be sure that arr[0]
is now the lowest value in the array we’re trying to sort and doesn’t need to be looked at again. In our hardcoded example after the first iteration of the outer loop arr[0] == 1. Hopefully the mechanism will become clearer as we go.
Moving into the inner loop, we always have j
starting at 1 index higher than i
to avoid wasting an iteration comparing two values that would ultimately be the same and wasting a loops’ worth of time. The if statement compares every value against arr[min_index]
by looking at the value in arr[j]
to determine which value is the smallest. min_index
may be updated multiple times if it the program keeps a finding lower number on each iteration of the inner loop. But they key thing is, when the inner loop has run length
times we have the index of the lowest value in the array from the yet to be sorted portion of the array.
for(int j = i + 1; j < length; j++){
if(arr[j] < arr[min_index]){
min_index = j;
}
}
By the time we get here:
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
we are now in a position to swap the values in the array because we know where the lowest value element is:
Copy the value of
arr[i]
into our temp holding variableCopy the value of
arr[min_index
] into the location atarr[i]
Copy the value of temp into
arr[min_index]
This has now swapped whatever was at arr[i] with the actual minimum value we found by scanning the array.
I found point 2 tricky to grasp ands it still catches me out when I drill myself on this.
To finish we just print the results in a loop
you should find this example outputs:
1,2,5,6,7,9
So the elements of the array are now sorted.
for(int i = 0; i < length; i++){
printf("%d\n", arr[i]);
}
Big 0
The time complexity of this algorithm is of the order of N² because we have nested loops. If we have an array of 10 items, the outer loop will run 10 times and the inner loop will also start 10 times although we have programmed it to not iterate unless needed, within reason. Each time the inner loop runs, remember because it starts at i + 1, the longer the program runs the less work each inner loop actually does. So it’s not strictly going to do 10 × 10 actions to complete if some items are already in the correct positions.
It turns out this algorithm will generally be a bit quicker than bubble sort in most applications. If you’re sorting masses of data though, this isn’t the algorithm for you. v