You are on page 1of 1

Week 7: Write C programs for implementing the following sorting methods to arrange a list of

integers in Ascending order : a) Insertion sort


#include<stdio.h>
void insertionsort(int a[20],int n);
void main()
{
int a[20],n,i;
printf("enter the values of n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the elements of
a[%d]",i);
scanf("%d",&a[i]);
}
insertionsort(a,n);
}
void insertionsort(int a[20],int n)
{
int i,j,index;
for(i=1;i<n;i++)
{
index=a[i];
j=i;
while((j>0)&&(a[j-1]>index))
{
a[j]=a[j-1];
j=j-1;

}
a[j]=index;
}
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
OUTPUT:
$ ./a.out
enter the values of n7
enter the elements of a[0]45
enter the elements of a[1]34
enter the elements of a[2]67
enter the elements of a[3]23
enter the elements of a[4]78
enter the elements of a[5]12
enter the elements of a[6]89
12
23
34
45
67
78
89
$

You might also like