Quicksort implementation, can't find error
I want to implement this quicksort algorithm with some different pivot strategy but there is some logical error in it. Can you please help me find it?
#include <iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
int arr[100],i,pivot,left,right,sum=0,a,n=10;
int partition();
void quickSort(int* ,int ,int );
void main()
{
clrscr();
int i,n=20;
for(i=0;i<=n;i++)
{
arr[i]=rand()%100;
}
for(i=0;i<=n;i++)
{
cout<<"\t"<<arr[i];
}
quickSort(arr,n,i);
for(i=1;i<n;i++)
{
cout<<"\n"<<arr[i];
}
getch();
}
int partition()
{
// int i;
// int sum=0;
// int pivot;
// stable_sort(arr,arr+3);
for(i=0;i<5;i++)
{
cout<<"\nsorted k elements\t"<<arr[i];
// sum=sum+arr[i];
}
// cout<<sum;
//cout<<"median is "<<sum/3;
pivot=arr[(i)/2];开发者_如何学编程
cout<<"pivotis value at position "<<pivot ;
return pivot;
}
void quickSort(int arr[],int left,int right)
{
partition();
right=n,left=0;
int i = right, j =left;
int tmp;
int p=pivot;
cout<<" m array of p"<<p;
while (i <= j) {
while (arr[i] < p)
i++;
while (arr[j] > p)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
if (left < j)
{
quickSort(arr, left, j);
}
if (i < right)
{
quickSort(arr, i, right);
}
}
Your pivot value will always be the value of arr[(i)/2]
, which is arr[2]
, no matter which portion of the array you happen to be sorting at the time. Pass the values of left
and right
to partition
so it knows which values to consider for the current call to quickSort
.
Also, the values of left
and right
that you pass for the initial call to quickSort
are 20 and 21, respectively, which surely isn't what you intended. You have an array of length 100, and you have initialized the first 21 elements, so you probably want to pass 0 and 21 for those parameters.
But the first thing you should probably do, if you want to test quicksort with a different pivot strategy, is to get it working first with a typical pivot strategy, like the one demonstrated in your textbook. Start with a working implementation, and only then should you start experimenting with variations. You should be able to find a working implementation in your textbook or your class notes.
I didn't find any place you compare values from the array.
I suppose you should check this place:
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
Probably it should be:
if (arr[i] < arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
精彩评论