C Program to Implement Insertion Sort

C Program to Implement Insertion Sort:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().



#include<stdio.h>
main()
{
   int i,j,num,temp,arr[20];

   printf("Enter total elements: ");
   scanf("%d",&num);

   printf("Enter %d elements: ",num);
   for(i=0;i<num;i++)
    {
      scanf("%d",&arr[i]);
    }

   for(i=1;i<num;i++)
    {
      temp=arr[i];
      j=i-1;
      while((temp<arr[j]) && (j>=0))
      {
         arr[j+1] = arr[j];
         j = j-1;
      }
      arr[j+1] = temp;
   }
   printf("After Sorting the Array: ");
   for(i=0;i<num;i++)
   {
      printf("%d\t",arr[i]);
   }
}

OUTPUT:

Enter total elements: 7
Enter 7 elements: 1 4 81 21 31 11 7
After Sorting the Array: 1      4       7       11      21      31      81

 

Leave a Reply

Your email address will not be published. Required fields are marked *

twelve − 7 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.