Saturday, 27 September 2014

Quick Sort

$$$ QUICK SORT $$$

PROGRAM:

#include<iostream>
int i,a[20],n;
class quicksort
{
public:
void getdata()
{
      cout<<"\nEnter the array limit:";
      cin>>n;
      cout<<"Enter array elements:";
      for(i=0;i<n;i++)
      {
            cin>>a[i];
      }

}

void qsort(int a[],int left,int right)
{
      int i,j,pivot,temp;
      if(left<right)
      {
            pivot=left;
            i=left+1;
            j=right;
            for(;;)
            {
                  while(a[i]<=a[pivot])
                        i=i+1;
                  while(a[j]>a[pivot])
                        j=j-1;
                  if(i<j)
                  {
                        temp=a[i];
                        a[i]=a[j];
                        a[j]=temp;
                  }
                  else
                  {
                        break;
                  }
            }
            temp=a[pivot];
            a[pivot]=a[j];
            a[j]=temp;
            qsort(a,left,j-1);
            qsort(a,j+1,right);
      }
}

void putdata()
{
      cout<<"The Sorted elements are:\t";
      for(i=0;i<n;i++)
      {
            cout<<a[i]<<"\t";
      }
}
};

void main()
{
      quicksort qs;
      cout<<"$$$ QUICK SORT $$$";
      qs.getdata();
      qs.qsort(a,0,n-1);
      qs.putdata();
}

OUTPUT:

$$$ QUICK SORT $$$
Enter the array limit:       8
Enter array elements:    40           20           70           14           60           61           97           30
The Sorted elements are:            14           20           30           40           60           61           70           97


1 comment: