Below simple quick sort code with last element as pivot,almost works but except the last element fails to get sorted. Any thoughts where this program went wrong?
Here's the output:
$a.out
4 3 5 2 1 3 2 3 //input
1 2 2 3 3 3 5 4 //output
Simple swap looks fine
void swap ( int* a, int* b )
{
int t = *a;
*a = *b;
*b = t;
}
Hmm..fine too ..may issue with end?
int partition(int a[],int start,int end){
int pivot = a[end];
int pindex=start;int i;
for ( i=start; i <= end-1; i++){
if (a[i] <= pivot){
swap(&a[i],&a[pindex]);pindex++;
}
}
swap(&a[pindex],&a[pivot]);
return (pindex + 1);
}
Surely looks good.
void quicksort(int a[],int start,int end){
int pindex;
if (start < end){
pindex = partition(a,start,end-1);
quicksort(a,start,pindex-1);
quicksort(a,pindex+1,end);
}
}
Simple main call
int main(){
int a[8] = {4, 3, 5, 2, 1, 3, 2, 3};
int i=0;
for(i=0;i<8;i++)
printf(" %d", a[i]);
quicksort(a,0,8);
printf("\n");
for(i=0;i<8;i++)
printf(" %d", a[i]);
}
Okay couple of changes
As doptimusprime pointed return pindex
int partition(int a[],int start,int end){
int pivot = a[end];
int pindex=start;int i;
for ( i=start; i <= end-1; i++){
if (a[i] <= pivot){
swap(&a[i],&a[pindex]);pindex++;
}
}
swap(&a[pindex],&a[end]);
return (pindex);
}
Adjust your quicksort function accordingly
void quicksort(int a[],int start,int end){
int pindex;
if (start < end){
pindex = partition(a,start,end-1);
quicksort(a,start,pindex); // no pindex-1
quicksort(a,pindex+1,end);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With