Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define cutoff 3
#define N 12
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int median(int a[],int left,int right); // function prototype
void printIt(int a[], int left, int right); // function prototype
void insertionsort(int A[],int n); // function prototype
void qsort(int a[],int left,int right); // function prototype
void quicksort(int a[],int n); // function prototype
int main()
{
int a[]={8,5,2,13,1,17,6,4,9,15,7,3};
printf("Unsorted array: \n8,5,2,13,1,17,6,4,9,15,7,3\n");
printIt(a, 0 , N);
quicksort(a,12);
int i;
for(i=0;i<12;i++)
{
printf("%d ",a[i]);
}
getch();
int median(int a[],int left,int right); // calling user-defined function
void printIt(int a[], int left, int right); // calling user-defined function
void insertionsort(int A[],int n); // calling user-defined function
void qsort(int a[],int left,int right); // calling user-defined function
void quicksort(int a[],int n); // calling user-defined function
printf("\n\t");
system("pause");
return 0;
int median(int a[],int left,int right); // function call
void printIt(int a[], int left, int right); // function call
void insertionsort(int A[],int n); // function call
void qsort(int a[],int left,int right); // function call
void quicksort(int a[],int n); // function call
return 0;
}
int median(int a[],int left,int right) /* User-defined function definition for median operation */
{
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 printIt(int a[], int left, int right) /* User-defined function definition for printIt operation */
{
int i;
for(i=left; i<right;i++)
printf("%2d ",a[i]);
printf("\n");
}
void insertionsort(int A[],int n) /* User-defined function definition for partition operation */
{
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) /* User-defined function definition for qsort operation */
{
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);
printIt(a, left, i-1);
qsort(a,i+1,right);
printIt(a, i+1, right);
}
else
insertionsort(a+left,right-left+1);
}
void quicksort(int a[],int n) /* User-defined function definition for quicksort operation */
{
qsort(a,0,n-1);
}