Just like the bubble sort algorithm, the selection sort is another simple sorting algorithm. With the algorithm, the list is split into 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 that it 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 the algorithm


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;
}
}
Share this post