Home » » Insertion sort code in C

Insertion sort code in C

Insertion sort program use backtracking for comparing current value with previous values and insert it to the desired place.  That's why it is called insertion sort. Its average complexity is O(n^2). Moreover it is slightly complex in understanding and coding. Yet very efficient sorting algorithm. Most likely to be asked in interview. Be prepare












// Insertion Sort Program


#include<conio.h>
#include<stdio.h>



void insertionSort(int a[],int );
void display(int a[],int );



void insertionSort(int a[],int max)
{
 int j;
 for(int i=1;i<max;i++)
 {
 
  j=i-1;
  int temp=a[i];
  while((j>=0)&&(temp<a[j]))
  {
   a[j+1]=a[j];
   j--;
  }
  a[j+1]=temp;
 }
}



void display(int a[],int mx)
{
 for(int i=0;i<mx;i++)
 printf("%d ",a[i]);
}


void main()
{
int a[12],n;
printf("Enter Number of Elements\n");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
 printf("Enter %d Array Elements\n",i);
 scanf("%d",&a[i]);
}
insertionSort(a,n);
display(a,n);
getch();
}








Share this article :

0 comments:

Post a Comment

 
My Other Websites : Ad Networks | Games Copyright © 2014. Study Depth - All Rights Reserved