Amazon Affiliate

Thursday 31 May 2012

PROGRAM FOR INSERTION SORT...

 // INSERTION SORT


 # include<iostream.h>

    class insertion_s
      {
        private: int key;

        public:
            int  insertion_sort(int *);  // prototype
            void display(int *, int);
       };

// definition of the insertion sort function

 int insertion_s :: insertion_sort(int list[])
         {
        cout<<"\nElement to be inserted Break condition is -0 : ";
        cin>>key;
        cout<<"\nSelected Element is :"<<key;
        int i = 0;
        int k ;

        while( key != -0 ) // -0 is break condition
        {
         k = i - 1;
         while((key < list[k]) && (k >= 0))
         {
          list[k+1] = list[k];
          --k;
         }

         list[k+1] = key ;
         cout<<"\n List after inserting an element ";
         for(int j = 0 ; j<=i; j++)
          cout<<"  "<<list[j];

          cout<<"\nElement to be inserted Break condition is -0: " ;
          cin>>key;
          cout<<"\nSelected Element is :"<<key;
          i ++;

      }
      return i;
    }

 // end of the insertion sort function

 // definition of the function

   void insertion_s :: display(int list[], int n)
       {
      cout<<"\n Final sorted list is as follows:\n";
      for(int j = 0 ; j < n ; j++)
      cout<<"  "<<list[j];
    }

// end of the display function

    void main()
           {
         insertion_s sort;
         int list[200];
         int n ;

         n = sort.insertion_sort(list);
         sort.display(list,n);
           }

No comments:

Post a Comment