Tuesday, 9 July 2013

source code: QuickSort using C++ [ simple, with little details and user friendly likewise ever ]

#include<iostream>
using namespace std;


class quicksort

{
public:
        int element_count, elements[100];

        void sorted_array();

        void sorting(int [], int, int);
        void partitioning(int [], int, int, int&);
        void display();
};


void quicksort :: sorted_array()

{
    cout <<"how many elements gonna be in the list?\nans: ";
    cin>> element_count;
    cout <<endl <<endl;

    cout <<"now insert elements 1 by 1 n do hit ENTER or SPACE afterwards every entry:\n=>";

    for(int h=0; h<element_count; h++)
        {
            cin>> elements[h];
        }
}

void quicksort :: sorting(int ary[], int lower_bound, int upper_bound)

{
    int x; //will be used as pointer

    if(lower_bound >= upper_bound)

        return;
 
    display();
 
    partitioning(ary, lower_bound, upper_bound, x);
    sorting(ary, lower_bound, x-1);        // right to left  check
    sorting(ary, x+1, upper_bound);        // left to right check
}

void quicksort :: partitioning(int x[], int lower_bound, int upper_bound, int &pj)

{
    int a= x[lower_bound], down= lower_bound, temp;

    upper_bound= upper_bound;


    while(down < upper_bound)

    {
        while(x[down] <= a)            // left to right check
            down++;
     
        while(x[upper_bound] > a)    // right to left  check
            upper_bound--;
     
        if(down < upper_bound)
        {
            temp= x[down];
            x[down]= x[upper_bound];
            x[upper_bound]= temp;
        }
    }


    x[lower_bound]= x[upper_bound];

    x[upper_bound]= a;
    pj= upper_bound;
}

void quicksort :: display()

{
    for(int h= 0; h<element_count; h++)
    {
        cout <<elements[h] <<" ";
    }
    cout<<endl;
}


int main()

{
    quicksort qs_obj;
    qs_obj.sorted_array();

    cout <<"\n\nnow showing each sorting in step by step process:\n";

    qs_obj.sorting(qs_obj.elements, 0, qs_obj.element_count-1);
 
    qs_obj.display();
}

No comments:

Post a Comment