The Selection sort algorithm

Just like the bubble sort algorithm, the selection sort is another simple sorting algorithm. With a selection sort, the list is split in two parts. One part contains sorted elements and the other part contains unsorted elements. When the algorithm runs, the list is sorted and grown from left to right. The difference between a bubble sort and the selection sort is the selection sort is faster. This is because the bubble sort needs more swaps due to the code being simpler and more stable.

Visual representation of how the selection sort runs

sorting algorithm diagram

C++ Implementation of Selection sort algorithm

</pre>
<pre>void Selection_Sort(int arr[], int n)
{
int position_min, temp;

for(int i =0; i < n−1; i++)
{
// Set the position min to the current index
// Of the array
position_min = i;

for(int k = i + 1; k < n; k++)
{
if(arr[k] < arr[position_min])
position_min = k;

// Position min will track the index that pos_min
// Is in. This is required when a swap happens
}

// If position min no longer equals i
// Than a smaller value must have been found
// Swap must occur
if(position_min != i)
{
temp = arr[i];
arr[i] = arr[position_min];
arr[position_min] = temp;
}
}
</pre>
<pre>
Share this post