Monday 2 February 2015

RANDOMIZED QUICK SORT C/C++ PROGRAM

Its obvious that Quick sort performs at O(nlogn) running time, but the worst case running time of Quick sort is O(n ^2).
When does this case happen? It happens when a pivot was chosen such that the array is not divided into two haves i.e
      consider 1,2,3,4,5 when 5 is chosen as pivot ,
AFTER PARTITION
                                             left subarray : 1,2,3,4
                                             right subarray : (empty)

when this trend continues we actually perform n times the sorting function and since each call performs a partition O(n) total complexity is O(n*n) i.e O(n^2)

Hence to avoid this situation we chose pivot randomly instead of choosing the last element as pivot(traditional way)

you can however argue that even choosing the pivot randomly can lead to worst case, but statistically the probablity for such case to occur is low compared to normal way.

Here is the C++ code (To Convert to C code just replace cin,cout with printf,scanf)

CODE:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int partition(int *a,int p,int r)
{
srand(time(0));
int pivot = rand()%(r-p);
pivot += p;
swap(a[r],a[pivot]);
pivot = r;
int temp = a[r];
int i = p-1;
for (int j = p; j < r ;j++) {
if ( a[j] <  temp ) {
i++;
swap (a[i],a[j]);
}
}
i++;
swap (a[r],a[i]);
return i;
}


void quicksort(int *a,int p,int r)
{
if (p < r)
{
int q = partition(a,p,r);
quicksort(a,p,q);
quicksort(a,q+1,r);
}
}

int main() {
// your code goes here
int a[] ={2,5,6,2,1,9,8};
quicksort (a,0,6);
for (int i=0;i<7;i++)
cout << a[i] << endl;
return 0;
}


No comments:

Post a Comment

Binary Search Algorithm Variations and Problems

Binary Search is a simple algorithm but is tricky when it comes to implementing it. The lower and upper bounds have to be set carefully to...