Tuesday, October 16, 2012

Insertion Sort algorithm in C++


Insertion Sort is a sorting algorithm used to sort an array element. From the name of the algorithm itself we can make out that here sorting is done with the help of insertion. Now suppose we are provided with a list of number e.g    18  16  14  17  8 . We have to arrange this number in a sorted order. In Insertion sort what it does that it will  pick the number present at the beginning of the given array say A, and place it in another array say B. And  then next number of the array A is picked up as a Key. Now it will compare  with the number present in array B if it is larger than that number then it will inserted in array B after the smaller number present in the array or if it is smaller than the existing number then it will be placed before the existing element of B. Similarly now the 3rd element is taken up as a Key and same comparison is done again. For rest of the element of array A same comparison is done.Have a look at this example.
       
         

/*Insertion Sort Program*/



#include<iostream.h>

#include<conio.h>
#define MAX 5
void insrtsort(int a[],int n)
{
int i,j,k;
for(i=1;i<=n;i++)
  {
  k=a[i];
  j=i-1;
  while(j>=0 && k<a[j])
   {
   a[j+1]=a[j];
   j--;
   }
   a[j+1]=k;
  }
}
void main()
{

int a[MAX];

int i,j;
clrscr();
cout<<"enter the list of number:\n";
for(i=0;i<MAX;i++)
{
cin>>a[i];
}
insrtsort(a,MAX);
cout<<"Sorted list is:\n";
for(i=1;i<=MAX;i++)
{
cout<<"\t"<<a[i];
}
getch();
}







No comments: