Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

quicksort program provides partially sorted output

Tags:

c

debugging

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]);
}
like image 706
wewmi Avatar asked Nov 19 '25 09:11

wewmi


1 Answers

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);
    }
}
like image 170
asio_guy Avatar answered Nov 21 '25 23:11

asio_guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!