Quick Sort Program in C
#include<stdio.h>
int partition(int a[100], int lb, int ub)
{
int up,dn,val,temp;
dn=lb+1;
up=ub;
val=a[lb];
while(dn<=up)
{
while(a[dn]<=val)
dn++;
while(a[up]>val)
up--;
if(dn<up)
{
temp=a[dn];
a[dn]=a[up];
a[up]=temp;
}
}
a[lb]=a[up];
a[up]=val;
return up;
}
void quicksort(int a[100], int lb, int ub, int n)
{
int p;
if(lb<ub)
{
p=partition(a,lb,ub);
quicksort(a,lb,p-1,n);
quicksort(a,p+1,ub,n);
}
}
void main()
{
int a[100],n,i;
printf("\nEnter no. of elements = ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("Enter number = ");
scanf("%d",&a[i]);
}
quicksort(a,0,n-1,n);
printf("\nSorted Array =\n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
Output :
Enter no. of elements = 4
Enter number = 9
Enter number = 3
Enter number = 7
Enter number = 5
Sorted Array =
3 5 7 9
Enter no. of elements = 5
Enter number = 51
Enter number = 42
Enter number = 33
Enter number = 24
Enter number = 15
Sorted Array =
15 24 33 42 51