Quick Sort

#include<iostream.h>
#include<conio.h>
class list
 {
public:
 int n,q[20],cmp_count,mov_count;
 list()
  {
cmp_count=0;
mov_count=0;
  }
 void read()
  {
 cout<<"\nEnter the number of elements:";
 cin>>n;
      cout<<"\nEnter the elements:\n";
      for(int i=0;i<n;i++)
       {
      cin>>q[i];
       }
  }
      void swap(int x,int y)
       {
      int temp;
      temp=q[x];
      q[x]=q[y];
      q[y]=temp;
       }
      void quick_sort(int low,int high)
       {
      int pivot,i,j;
      if(low>high)
       return;
      i=low+1;
      j=high;
      pivot=q[low];
      while(i<=j)
       {
        while((q[i]<=pivot)&&(i<=high))
         {
       i++;
       cmp_count++;
         }
        cmp_count++;
        while((q[j]>pivot)&&(j>=low))
         {
       j--;
       cmp_count++;
         }
       cmp_count++;
       if(i<j)
        {
         swap(i,j);
          mov_count++;
        }
           }
          if(low<j)
      {
        swap(low,j);
        mov_count++;
           }
      quick_sort(low,j-1);
           quick_sort(j+1,high);
         }
             void display()
              {
                 cout<<"The sorted elements are:\n";
           for(int j=0;j<n;j++)
             {
          cout<<q[j]<<endl;
             }
           cout<<"\nNumber of comparisons:"<<cmp_count;
           cout<<"\nNumber of data movements:"<<mov_count;
              }
        int getsize()
               {
             return(n);
              }
    };
   void main()
    {
           clrscr();
     list l;
     l.read();
           l.quick_sort(0,l.getsize()-1);
           l.display();
           getch();
    }

No comments:

Related Posts with Thumbnails