#include <stdio.h>
int main()
{
int i, j, s = 0, key = 0;
// program to demonstrate insertion sort
printf("Enter size of array : ") ;
scanf("%d", &s) ;
if (s == 0)
{
printf("nothing to sort.") ;
return 0 ;
}
else
{
// initialize the array of size s
int a[s] ;
// create the array
for (i = 0 ; i < s ; i ++)
{
printf("enter element at position %d: ", i) ;
scanf("%d", &a[i]) ;
}
// print the unsorted array
printf("Unsorted array is: \n") ;
for (i = 0 ; i < s; i ++)
{
printf("%d\t", a[i]) ;
}
// sort the array
for (j = 1; j < s; j ++)
{
key = a[j] ;
i = j - 1;
while(i >= 0 && a[i] > key)
{
a[i + 1] = a[i] ;
i = i - 1 ;
}
a[i + 1] = key ;
}
// print the sorted array
printf("\nSorted array is: \n") ;
for (i = 0 ; i < s; i ++)
{
printf("%d\t", a[i]) ;
}
return 0 ;
}
}