Our Feeds

Monday, 16 November 2015

AJITH KP

Quicksort - Hoare partition scheme in C++

Hello GuyZ,
     This is another question you have to be solved in your MCA/BCA/BTech cource. The source code is to solve Quicksort in Hoare partition scheme.



Source Code
/*
    Coded By Ajith Kp
    [] http://www.terminalcoders.blogspot.com []
*/
#include <iostream>
using namespace std;
class quick
{
    int a[100], n, i, j;
    public:
        void read()
        {
            cout<<"Enter the limit: ";
            cin>>n;
            cout<<"Enter "<<n<<" Elements: ";
            for(i=0;i<n;i++)
            {
                cin>>a[i];
            }
            quick_sort(0, n-1);
            cout<<"Sorted List: ";
            for(i=0;i<n;i++)
            {
                cout<<a[i]<<" ";
            }
            cout<<"\n";
        }
        
        void quick_sort(int f, int l)
        {
            int j;
            if(f<l)
            {
                j = partition(f, l);
                quick_sort(f, j);
                quick_sort(j+1, l);
            }
        }
        int partition(int f, int l)
        {
            int pivot, i, j, tmp;
            pivot = a[f];
            i = f-1;
            j = l+1;
            while(1){
                do{
                    j--;
                }while(a[j]>pivot);
                do{
                    i++;
                }while(a[i]<pivot);
                if(i<j){
                    swap(i, j);
                }
                else return j;
            }
        }
        void swap(int i, int j)
        {
            int tmp;
            tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
};
int main()
{
    quick q;
    q.read();
    cin.get();
}