Sunday, October 2, 2011

Quick Sort C program for Dev C++

 #include <stdio.h>  
#define cutoff 3
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int median(int a[],int left,int right)
{
int center=(left+right)/2;
if(a[left]>a[center])
swap(&a[left],&a[center]);
if(a[left]>a[right])
swap(&a[left],&a[right]);
if(a[right]<a[center])
swap(&a[right],&a[center]);
swap(&a[center],&a[right-1]);
return a[right-1];
}
void insertionsort(int A[],int n)
{
int j,p,temp;
for(p=1;p<n;p++)
{
temp=A[p];
for(j=p;j>0&&A[j-1]>temp;j--)
A[j]=A[j-1];
A[j]=temp;
}
}
void qsort(int a[],int left,int right)
{
int i,j,pivot;
if(left+cutoff<=right)
{
pivot=median(a,left,right);
i=left;
j=right-1;
while(1)
{
while(a[++i]<pivot){}
while(a[--j]>pivot){}
if(i<j)
swap(&a[i],&a[j]);
else
break;
}
swap(&a[i],&a[right-1]);
qsort(a,left,i-1);
qsort(a,i+1,right);
}
else
insertionsort(a+left,right-left+1);
}
void quicksort(int a[],int n)
{
qsort(a,0,n-1);
}
int main()
{
int a[]={1,5,7,2,0,-1,5,43,23,60};
quicksort(a,10);
int i;
for(i=0;i<10;i++)
{
printf("%d ",a[i]);
}
getch();
}

No comments:

Post a Comment