Tuesday, July 10, 2018

Program 14


INSERTION SORT
Write a C++ program to accept a single dimensional array and sort given array elements by Insertion Sort.

#include<iostream.h>
#include<conio.h>
#include<limits.h>

void inssort(int[],int);

void main()
{
 clrscr();
 int a[50],item,n,index;
 cout<<"Enter array size ";
 cin>>n;
 cout<<"\nEnter array elements :";
 for(int i=0;i<=n;i++)
cin>>a[i];
 inssort(a,n);
 cout<<"\n\nThe sorted array is as shown below \n";
 for(i=1;i<=n;i++)
cout<<a[i]<<" ";
 cout<<endl;
 getch();
}

void inssort(int a[],int size)
{
 int j,tmp;
 a[0]=INT_MIN;
 for(int i=1;i<=size;i++)
 {
  tmp=a[i];
  j=i-1;
  while(tmp<a[j])
  {
   a[j+1]=a[j];
   j--;
  }
  a[j+1]=tmp;
  cout<<"\nArray after pass - "<<i<<" - is:";
  for(int k=1;k<=size;k++)
         cout<<a[k]<<" ";
  cout<<endl;
 }
}

No comments:

Post a Comment