/* QUICK sort for numbers.Use step count,swap count,comparison count
*/
#include<stdio.h>
int stepcount=0,swapcount=0,compcount=0;
void quick_sort(int [],int,int);
int partition(int [],int,int);
int main()
{
int a[50],n,i;
printf("\nEnter no of elements :");
scanf("%d",&n);
printf("\nEnter array elements :");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nUnsorted Data:");
for(i=0;i<n;i++)
printf("%5d",a[i]);
quick_sort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n No. of steps= %d",stepcount);
printf("\n No. of swaps= %d", swapcount);
printf("\n No. of comparisons= %d",compcount);
}
void quick_sort(int a[],int l,int u){
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}
int partition(int a[],int l,int u)
{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;
do
{
do
{ i++;
compcount++;
stepcount+=2;
}while(a[i]<v && i<=u);
do
{ j--;
compcount++;
stepcount+=2;
}while(a[j]>v);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
swapcount++;
stepcount+=4;
}
}while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
}
No comments:
Post a Comment