Monday, January 13, 2014

Quick Sort program - C version



As the name implies, it is quick, and it is the algorithm generally preferred for sorting.The steps involved are



Pick an element, say P (the pivot) .Re-arrange the elements into 3 sub-blocks,
                              
                               1. those less than or equal to ( ≤ ) P (the  left- block  S1 )

                               2. P (the only element in the  middle -block)

                               3. those greater than or equal to ( ≥ )  P (the  right- block  S2 )

Repeat the process recursively for the  left- and  right- sub-blocks.

Return {quicksort(S1 ), P , quicksort( S2 )}.

(That is the results of quicksort(S1), followed by P, followed by the results of quicksort(S2))

Quick Sort Program 

#include<conio.h>
void main()
{
int i,k,l=1,u,n,a[20];
void qsort(int a[],int l,int u);
clrscr();
printf("Enter number of elements");
scanf("%d",&n);
printf(" Enter  elements");
for (i=1; i<=n;i++)
scanf("%d",&a[i]);
u=n;
qsort(a,l,u);
for(i=1;i<=n;i++)
printf("%5d",a[i]);
getch();
}
void qsort(int a[],int l,int u)
{
int i,j,t, flag=1,key;
i=l;
j=u+1;
if(l<u)
{
key=a[i]; // pivot point
while(  flag==1)   // spitting the block pf datadata into 2 . A sublock containg data less then key and the   
                           //other greater than  key                 
{
i++;
while (a[i]<key)
i++;
j--;
while (a[j]>key)

j--;
if(i<j)    // swap the key to make it the center of the 2 sub block
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
else
 flag=0;
}
t=a[l];
a[l]=a[j];
a[j]=t;
qsort(a,l,j-1);  //recursively calling qsort to sort lower sub block
qsort( a,j+1, u);   //recursively calling qsort to sort upper sub block
}
}

No comments:

Post a Comment