PROGRAM FOR RANDOMIZED QUICKORT USING C++ Gain Infiniti

PROGRAM FOR RANDOMIZED QUICKORT USING C++


//The Advantages of Randomization in QS :
//--> The Pivot is chosen randomly.It is equilikely to be
//      any element between p and r.
//--> The Probability that the partition will be unbalanced is minimized.
//      Since choosing the pivot as the last/first element of the array
//      increases the chance of encountering the worst case (sorted Array).

#include <iostream>
#include <stdlib>
#include <time>
using namespace std;
#define SIZE 5

class RandomizedQuickSort
{
    public:
    int *array;
    void sort(int*,int,int);
    int partition(int*,int,int);
    int randomizedPartition(int*,int,int);
    void init();
    void disp();
    void sort_start();
    RandomizedQuickSort()
    {
        srand(time(NULL));
        array=new int[SIZE];
    }
    ~RandomizedQuickSort()
    {
        delete[] array;
    }
};

void RandomizedQuickSort::initial()
{
    for(int i=0;i<SIZE;i++)
    {
        cout<<"Enter the "<<i<<" th index = ";
        cin>>array[i];
    }
}
void RandomizedQuickSort::display()
{
    for(int i=0;i<SIZE;i++)
    {
        cout<<"The "<<i<<" th index = "<<array[i]<<"\n";
    }
}

//T(n)=O(n)
int RandomizedQuickSort::partition(int* ar,int p,int r)
{
    int x=ar[r];
    int i=p-1;
    for(int j=p;j<r;j++)
    {
        if(ar[j] <= x)
        {
            i++;
            int t=ar[j];
            ar[j]=ar[i];
            ar[i]=t;
        }
       
    }
    int t=ar[i+1];
    ar[i+1]=ar[r];
    ar[r]=t;
    return (i+1);
}

//T(n)=O(n)
int RandomizedQuickSort::randomizedPartition(int* ar,int p,int r)
{
    int pos;
    int i=p+ rand()%(r-p+1);  //randomizedposition
    int tmp=ar[r];
    ar[r]=ar[i];
    ar[i]=tmp;
    pos=partition(ar,p,r);
    return pos;
}

//WorstCase T(n)=O(n^2)
//BestCase T(n)=O(lg n)
//AverageCase T(n)=O(n lg n)

void RandomizedQuickSort::sort(int* ar,int p,int r)
{
    int q;
    if(p<r)
    {
        q=randomizedPartition(ar,p,r);
        sort(ar,p,q-1);
        sort(ar,q+1,r);
    }
}

void RandomizedQuickSort::sort_start()
{
    sort(array,0,SIZE-1);
}
 main()
{
    RandomizedQuickSort object;
    object.initial();
    object.sort_start();
    object.display();
}

/*
OUTPUT:-

Enter the 0 th index = 5
Enter the 1 th index = 4
Enter the 2 th index = 3
Enter the 3 th index = 2
Enter the 4 th index = 1
The 0 th index = 1
The 1 th index = 2
The 2 th index = 3
The 3 th index = 4
The 4 th index = 5

*/

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 

Design By Manish and Ranjan