Friday, 7 December 2012

Insertion sort cpp program

CPP Program to implement  insertion sort

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;

class array
{ private:
          int arr[MAX];
          int count;
  public:
          array()
          { count=0;}
          void add(int);
          void display();
          void sort();
};
void array::add(int item)
{        if(count<MAX)
          {        arr[count]=item;
                    count++;
          }
          else
                   cout<<"\nArray is full";
}
void array::display(void)
{        cout<< "\nThere are"<<count<<" elements in the list \n";
          cout<<"\n They are : \n";
          for(int i=0;i<count;i++)
                   cout<<arr[i]<<" ";
}
void array::sort()
{        for(int i=0;i<count;i++)
          {        int value=arr[i];
                    for(int j=i-1;((j>=0)&&(arr[j]>value));j--)
                             arr[j+1]=arr[j];
                    arr[j+1]=value;
          }
          return;
}
void main()
{        int element,n,i,c;
          array insertion;
          while(1)
          {        clrscr();
                   cout<<"\nPerform the Insertion Sort";
                   cout<<"\n-------------------------------";
                   cout<<"\n1.Input data into the list";
                   cout<<"\n2.Display data in the list";
                   cout<<"\n3.Sort the list";
                   cout<<"\n4.Exit from the program";
                   do
                    {        cout<<"\nSelect your choice(1:4)";
                             cin>>c;
                             cout<<"";
                    }
                   while((c<1)||(c>4));
          if(c==4)exit(1);
          clrscr();
          switch(c)
                    { case 1 :    
clrscr();
                             cout<<"How many elements : ";
                             cin>>n;
                             for(i=0;i<n;i++)
                             {        cout<<"Enter a number " <<i+1<< " : ";
                                      cin>>element;
                                      insertion.add(element);
                             }
                             break;
                   case 2 :
                   clrscr();
                             insertion.display();
                             break;
                   case 3 :
                             clrscr();
                             insertion.sort();
                             cout<<"List is successfully sorted \n";
                             break;
                   }
          cout<<"\nPress any key to continue............";
          getch();
          }
}

No comments:

Post a Comment