Sorting in C is mainly done to arrange elements either in ascending or in descending order.
Sorting in done in programming by various ways
We are about to discuss insertion sort that will take element wise comparison for performing sorting.

In the given figure it is clearly understood that first element is compared with the second one and swapping is done in the first iteration.
After this in the second iteration first element is compared with second and then third element and swapping is done whichever is lower will comes in the first position.
/*Sorting Elements of an array in ascending order using insertion sort algorithm*/
#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j] in above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}
0 Comment(s)