QUICK SORT PROGRAM

QUICK SORT
#include<stdio.h>
#include<conio.h>


void qsort(int [ ], int, int);

void main()
{
int a[10], n, i, lb, ub;
clrscr();
printf("\n Enter the n value: ");
scanf("%d",&n);
printf("\n Enter the %d array elements: ",n);
for(i=1; i<=n ;i++)
scanf("%d",&a[i]);
lb=1;
ub=n+1;
printf("\n Before sorting the given array is:" );
for(i=1; i<=n; i++)
printf("%4d",a[i]);
qsort(a, lb, ub);
printf("\n\n\n After sorting the given array is: ");
for(i=1; i<=n; i++)
printf("%4d",a[i]);
getch();
}

void qsort(int a[ ], int lb, int ub)
{
int flag=1,i,j,temp,pivot;
if(lb<ub)
{
                                   i=lb;
                                   j=ub+1;
                                   pivot=a[lb];

                                   while(flag)
                                   {
                                               i=i+1;
                                               while(a[i]<pivot)
                                               {
                                                           i++;
                                               }

                                                j=j-1;
                                               while(a[j]>pivot)
                                               {
                                                           j--;
                                               }

                                               if(i<j)
                                               {
                                               temp=a[i];
                                               a[i]=a[j];
                                               a[j]=temp;
                                               }
                                               else
                                               {
                                               flag=0;
                                               }
                                   }
                                   temp=a[lb];
                                   a[lb]= a[j];
                                   a[j]=temp;
                                   qsort(a, lb, j-1);
                                   qsort(a, j+1, ub);
}

}
Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment