Saturday, 10 May 2014

Quick Sort

PROGRAM:

#include<stdio.h>
#include<conio.h>
void qsort(int a[],int,int);
void main()
{
                int i,a[20],n;
                clrscr();
                printf("$$$ QUICK SORT $$$");
                printf("\nEnter the array limit:");
                scanf("%d",&n);
                printf("Enter array elements:");
                for(i=0;i<n;i++)
                {
                                scanf("%d",&a[i]);
                }
                qsort(a,0,n-1);
                printf("The Sorted elements are:\t");
                for(i=0;i<n;i++)
                {
                                printf("%d\t",a[i]);
                }
                getch();
}

void qsort(int a[],int left,int right)
{
                int i,j,pivot,temp;
                if(left<right)
                {
                                pivot=left;
                                i=left+1;
                                j=right;
                                for(;;)
                                {
                                                while(a[i]<=a[pivot])
                                                                i=i+1;
                                                while(a[j]>a[pivot])
                                                                j=j-1;
                                                if(i<j)
                                                {
                                                                temp=a[i];
                                                                a[i]=a[j];
                                                                a[j]=temp;
                                                }
                                                else
                                                {
                                                                break;
                                                }
                                }
                                temp=a[pivot];
                                a[pivot]=a[j];
                                a[j]=temp;
                                qsort(a,left,j-1);
                                qsort(a,j+1,right);
                }
}

OUTPUT:
$$$ QUICK SORT $$$
Enter the array limit:       8
Enter array elements:    40           20           70           14           60           61           97           30
The Sorted elements are:            14           20           30           40           60           61           70           97

No comments:

Post a Comment