# Quicksort: Unable to get the desired output, Segmentation_Fault

#include<stdio.h>
//quicksort
void quicksort(int a[], int, int);
int partition(int a[],int ,int);
int main()
{
int i,j,a[33],n,p,r,q;
printf(“Enter the total number for sorting\n”);
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf(“Enter the number in array\n”);
scanf("%d", &a[i]);
}
p=i;
r=n-1;
quicksort(a,p,r);
for (i=0;i<n;i++)
{
printf("\n sorted element %d",a[i]);
}
return 0;

``````	}
void quicksort(int a[33],int p,int r)
{
int q;
if(p<r)
q=partition(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
int partition(int a[33], int p, int r)
{
int x,i, temp;
x=a[r];
i=p-1;
for (int j=p;j<r-1;j++)
{
if(a[j]<=x)
{
i=i+1;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[i+1];
a[i+1]=a[r];
a[r]=temp;
return i+1;
}``````

Hey @rajni,

• Your problem lies in quicksort
function, because quicksort is
running for some garbage value (p >
r). I think you forgot to put if
condition under curly braces.
• After that second error is p should
be 0 instead of i. (main function)
• In function partition, the for loop should go upto <= r-1, instead of < r-1.

Here is the corrected code link.

Hope this helps!

void quicksort(int a[33],int p,int r)
{
int q;

``````    if(p<r)
q=partition(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
``````

Thank you so much @sandeep_007!

Now program is working.
Can you the please check the code of the following link of heapsort.
https://discuss.codechef.com/questions/109497/heapsort_-unable-to-execute_error-segmentation_fault