Code:
#include <stdio.h>
#include <conio.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()
{
printf("Unsorted array:\n8,5,2,13,1,17,6,4,9,15,7,3\n");
printf("Sorted array: \n");
int a[]={8,5,2,13,1,17,6,4,9,15,7,3};
quicksort(a,12);
int i;
for(i=0;i<12;i++)
{
printf("%d ",a[i]);
}
getch();
}