Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
// Program to implement Quick sort

#include<iostream.h>
#include<iomanip.h>

class quicksort
{
     private:
          int *x;
          int items;
     public:
          quicksort(int);
          ~quicksort();
          void input(int []);
          void display();
          void sort(int,int);
};


quicksort::quicksort(int n)
{
     items=n;
     x=new int[items];
}


quicksort::~quicksort()
{
     delete [] x;
}


void quicksort::input(int a[])
{
     for(int i=0;i<items;i++)
     x[i]=a[i];
}


void quicksort::display()
{
     cout<<"\n Sorted elements are :";
     for(int i=0;i<items;i++)
     cout<<setw(3)<<x[i];
}


void quicksort::sort(int first,int last)
{
     int temp;
     if(first<last)
     {
          int pivot=x[first];
          int i=first;
          int j=last;
          while(i<j)
          {
                    while(x[i]<=pivot &&i<last)
                    i++;
                    while(x[j]>=pivot && j>first)
                    j--;
                    if(i<j)
                    {
                         temp=x[i];
                         x[i]=x[j];
                         x[j]=temp;
                    }
          }
          temp=x[first];
          x[first]=x[j];
          x[j]=temp;
          sort(first,j-1);
          sort(j+1,last);
     }
}




int main()
{
     int elements[100],n;
     cout<<"Enter how many elements \n";
     cin>>n;
     cout<<"Enter"<<n<<"elements \n";
     for(int i=0;i<n;i++)
     cin>>elements[i];
     quicksort obj(n);
     obj.input(elements);
     obj.sort(0,n-1);
     obj.display();
     return 0;
}



Test data

Enter how many elements
7
Enter 7 elements
10  90  12  11  43  34  22

Output
Sorted elements are : 10  11  12  22  34  43  90