Sunday 23 October 2011

Program for Quick Sort


#include<iostream>
#include<cstdlib>
using namespace std;
class sort
{
        int a[20],b[20];
        int low,high;
        public:
                int n;
                int get();
                void getdata();
                void quicksort(int,int);
                void display();

};
void sort::getdata()
{
        cout<<"enter the number of elements in the array";
        cin>>n;
        cout<<"enter the elements";
        for(int i=0;i<n;i++)
                cin>>b[i];
}
int sort::get()
{
   return n;
}
void sort::quicksort(int low,int high)
{
    int p,i,j,t;
    p=i=low,j=high;
    if(i<j)
    {
       while(i<j)
       {
          while(b[p]<b[j])
            j--;
            if(b[p]>b[j])
              {
                 t=b[p];
                 b[p]=b[j];
                 b[j]=t;
                 p=j;
              }
                while(b[p]>b[i])
                    i++;
                   if(b[p]<b[i])
                   {
                        t=b[i];
                        b[i]=b[p];
                        b[p]=t;
                        p=i;
                   }
                        if(i>=j)
                         {
                             quicksort(low,i-1);
                             quicksort(i+1,high);
                         }
        }
     }
}
void sort::display()
{
        cout<<"the sorted list is\n";
        for(int i=0;i<n;i++)
                                               {
                cout<<b[i]<<"\t";
        }
}
int main()
{
        sort a;
        int op;
        while(1)
        {
                cout<<"enter the option\n";
                cout<<"1.get data\n2.quick sort\n3.display\n4.exit\n";
                cin>>op;
                switch(op)
                {
                        case 1:
                                a.getdata();
                                break;
                        case 2:
                                a.get();
                                a.quicksort(0,a.n-1);
                                break;
                        case 3:
                                a.display();
                                break;
                        case 4:
                                exit(1);
                }
        }
}


OUTPUT:-

enter the option
1.get data
2.quick sort
3.display
4.exit
1
enter the number of elements in the array5
enter the elements2
1
3
6
7
enter the option
1.get data
2.quick sort
3.display
4.exit
3
the sorted list is
2       1       3       6       7       enter the option
1.get data
2.quick sort
3.display
4.exit
2
enter the option
1.get data
2.quick sort
3.display
4.exit
3
the sorted list is
1       2       3       6       7       enter the option
1.get data
2.quick sort
3.display
4.exit
4


No comments:

Post a Comment