How to partition an array
There is some problem in the following code that seeks to partition the array (the first element taken as pivot). Please help me fix the issue.
Code:
#include<stdio.h>
#include<conio.h>
int partition(int [],int,int);
main()
{
int a[20],n,i;
printf("enter the number of elements in the array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the number\n");
scanf("%d",a+i);
}
printf("the index of the pivot is %d and the partitioned array is\n",partition(a,0,n-1));
for(i=0;i<n;i++) printf("%d\t",a+i);
getch();
}
int partition(int a[],int lower,int upper)
{
int p=a[lower];
int i=lower,j=upper+1,temp;
do
{ do{i++;}while(a[i]<=p);
do{j--;}while(a[j]>=p);
if(i<j){ temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i>=j);
a[lower]=a[j];
a[j]=p;
return j;
}