The following is a program to implement quick sort. If you have any doubts, please let me know.
#include<stdio.h>
void
quicksort(int [50],int,int);
main()
{
int a[50],n,i;
printf("\nEnter size of the array:
");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nBefore Sorting:\n");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
quicksort(a,0,n-1);
printf("\nSorted elements:\n ");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
printf("\n");
}
void
quicksort(int a[50],int left,int right)
{ int pivot,j,temp,i;
if(left<right)
{
pivot=left;
i=left;
j=right;
while(i<j)
{
while(a[i]<=a[pivot]&&i<right)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,left,j-1);
quicksort(a,j+1,right);
}
}
No comments:
Post a Comment