Summary: this tutorial explains how the selection sort algorithm works and shows you how to implement the selection sort in C.
Introduction to the selection sort algorithm
The selection sort is a simple sorting algorithm. The following illustrates the steps of the selection sort algorithm:
- Find the minimum element in the list.
- Swap it with the element in the first position of the list.
- Repeat the steps above for all remaining elements of the list starting from the second position.
The complexity of the selection sort algorithm in the worst case is O(n2). The selection sort technique is less efficient on a large list. It generally performs worse than the insertion sort technique.
Selection sort in C
The following is the selection sort in C implementation.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
void swap(int *x,int *y);
void selection_sort(int* a, const int n);
void display(int a[],int size);
void main()
{
int a[SIZE] = {8,5,2,3,1,6,9,4,0,7};
int i;
printf("The array before sorting:\n");
display(a,SIZE);
selection_sort(a,SIZE);
printf("The array after sorting:\n");
display(a,SIZE);
}
/*
swap two integers
*/
void swap(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
/*
perform selection sort
*/
void selection_sort(int* a,const int size)
{
int i, j, min;
for (i = 0; i < size - 1; i++)
{
min = i;
for (j = i + 1; j < size; j++)
{
if (a[j] < a[min])
{
min = j;
}
}
swap(&a[i], &a[min]);
}
}
/*
display array content
*/
void display(int a[],const int size)
{
int i;
for(i=0; i<size; i++)
printf("%d ",a[i]);
printf("\n");
}
Code language: C++ (cpp)
The following is the output of the selection sort program above:
The array before sorting:
8 5 2 3 1 6 9 4 0 7
The array after sorting:
0 1 2 3 4 5 6 7 8 9
Code language: C++ (cpp)
In this tutorial, we have introduced you to selection sort algorithm and implemented the selection sort in C.
Was this tutorial helpful ?