In this tutorial, you will learn the concept of selection sort in c programming used for sorting arrays.
The selection sort algorithm compares two successive elements of an array repeatedly and swapping if necessary. This is the simple sorting algorithm used in C programming.
If the user wants to sort an array in ascending order then the comparison is made between two elements and the smaller element is placed at the first place. The process is repeated until last elements are compared. Hence, if there are n elements in the array, the total number of comparison are n-1.
[adsense1]
For proper understanding of program you must be familiar with following concepts of C programming
/* sorting array using selection sort method */
#include <stdio.h>
#define SIZE 5
int main ()
{
int data[ SIZE ] = { 3, 12, 7, 10, 5};
int pass, i, temp;
printf("Original order of data items:\n");
//printing data items
for ( i = 0; i < SIZE; ++i)
{
printf("%4d", data[ i ]);
}
//selection sort algorithm
for (pass = 0; pass < SIZE; ++pass)
{
for ( i = pass + 1; i < SIZE; ++i)
{
if ( data[ pass ] > data[ i ])
{
//steps for swapping
temp = data[ pass ];
data[ pass ] = data [ i ];
data[ i ] = temp;
}
}
}
printf("\n\nData items in ascending order:\n");
for (i= 0; i < SIZE; ++i)
{
printf("%4d", data[ i ]);
}
return 0;
}
Output
Explanation
In the above example, we have sorted data elements of an array in ascending order. We have defined macro SIZE
which is set to 5. The total number of the pass in the above program for sorting are 4.
If the user wants to sort data items of the array in descending order following change should be made in the condition of if
.
if ( data[ pass ] < data[ i ])
Now elements of the arrays are sorted in descending order.