Tuesday, June 29, 2010

quick sort -C++

 
Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.
The steps are:
  1. Pick an element, called a pivot, from the list.
  2. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements.
  4. Worst case performance O(n2)
    Best case performance O(nlogn)


---------------------------------------------------
#include<iostream>
#define N 10
using namespace std;

class QuickSort
{
private:
int low,high;

double *Plist;
public:
QuickSort(int,int,double *,int);

void qkSort();
int part();
void prnt(int);
~QuickSort();
};

QuickSort::QuickSort(int l, int h,double *list, int ListLong)
{

low = l;
high = h;
Plist = new double[ListLong];

for(int i=0;i<ListLong;i++) Plist[i]=list[i];
}

int QuickSort::part()
{
int i,j;
double p;

i=low; j=high;
p=Plist[low];


while(i<j)
{
while(i<j &&Plist[j]>=p)
{

j--;
}
Plist[i]=Plist[j];
while(i<j &&Plist[i]<=p) i++;

Plist[j]=Plist[i];
}
Plist[i] = p;

return(i);
}
void QuickSort::qkSort()
{
int i;

if(low<high)
{
i =part();
high=i-1;

qkSort();
low = i+1;
qkSort();
}

else
return;
}
void QuickSort::prnt(int N)
{
cout<<"Sort sequence is "<<endl;

for(int i=0;i<N;i++)
cout << Plist[i] <<endl;
}

QuickSort::~QuickSort()
{
delete []Plist;
}

double a[]={3.0,3.7,3.5,2.9,2.7,2.3,3.3,2.5,3.1,3.9};

int main()
{
int m=0, n=N-1;

QuickSort qs(m,n,a,N);
qs.prnt(N);

qs.qkSort();
qs.qkSort();
qs.prnt(N);

return(0);
}

No comments:

Post a Comment