C program for quicksort(recursive)

721 views Asked by At

The following c program is a quicksort recursive program. Although I have written this code according to the Cormen explanation, yet it is incorrectly sorting the input.For example it is sorting the input 3,8,1 to 3,1,8. Thanks a lot in advance for finding the mistake

#include<stdio.h>
void printa(int a[],int size)
{
    int i;
    printf("\n");
    for(i=0;i<size;i++)
    {
        printf("%d\n",a[i]);
    }
}
void swap(int *a,int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}
int partition(int a[],int p,int r)
{
    int i,j,x;
    i=p-1;
    x=a[r];
    for(j=p;j<r;j++)
    {
        if(a[j]<=x)
        {
            i=i+1;
            swap(&a[i],&a[j]);
        }
        swap(&a[i+1],&a[r]);
    }
    return i+1;
}
void quicksort(int a[],int p,int r)
{
    if(p<r)
    {
    int q;
    q=partition(a,p,r);
    quicksort(a,p,q);
    quicksort(a,q+1,r);
    }
}
main()
{
    int a[50],i,size;
    printf("enter the size of the array\n");
    scanf("%d",&size);
    printf("enter the elements of the array\n");
    for(i=0;i<size;i++)
    {
        scanf("%d",&a[i]);
    }
    quicksort(a,0,size-1);
    printa(a,size);

}
0

There are 0 answers