/********************************************************\
* *************** ************** *
* * * INSERTION SORT * * *
* *************** ************** *
/********************************************************/
#include <iostream.h>
#include <conio.h>
#include <malloc.h>
void insert(int a[],int n);
void main()
{
int i,n;
int* a;
clrscr();
cout << "Enter the no. of elements: ";
cin >> n;
a = (int*) malloc(sizeof(int)*n);
cout << "\nEnter the elements :\n\n";
for(i=0;i<n;i++)
{
cin >> a[i];
}
insert(a,n);
cout << "\nSorted array is: ";
for(i=0;i<n;i++)
{
cout << a[i] << " ";
}
getch();
}
void insert(int a[],int n)
{
int j,k,t;
for(k=1;k<n;k++)
{
t=a[k];
j=k-1;
while((t<a[j]) && (j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=t;
}
}
No comments:
Post a Comment