C Program:Insertion Sort


This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.

//Insertion by Vikas Konaparthi
#include <stdio.h>
void insert(int a[10],int size);
void ReadArray(int a[10],int size);
void WriteArray(int a[10],int size);

void ReadArray(int a[10],int size)
{
    int i;
    printf("\n Enter %d elements",size);
    for(i=0;i<size;i++)
    scanf("%d",&a[i]);
}
void WriteArray(int a[10],int size)
{
    int i;
    printf("\n Sorted Array\n");
    for(i=0;i<size;i++)
    {
        printf("%d\t",a[i]);
    } 
}
void insert(int a[10],int size)
{
  int i,j,temp;
  for(i=0;i<size;i++)
  {
      temp=a[i];
      j=i;
      while((j>0)&&(a[j-1]>temp))
      {
          a[j]=a[j-1];
          j=j-1;
      }
      a[j]=temp;
  }
    }
   
void main()
{
    int a[10],size;
    printf("\nEnter the size of array");
    scanf("%d",&size);
    ReadArray(a,size);
    insert(a,size);
    WriteArray(a,size);

Recommended: solve it on “PRACTICE ” first, before moving on to the solution.

Previous Post Next Post