14 April, 2012

quick sort

#include<stdio.h>
void quicksort(int *a,int left,int right)
{
        if(left<right)
        {
        int pivot,t,i,j;
        pivot=left;
        i=left;
        j=right;
        while(i<j)
        {
                while(a[i]<=a[pivot]&&i<right)
                i++;
                while(a[j]>a[pivot])
                j--;
                if(i<j)
                {
                        t=a[i];
                        a[i]=a[j];
                        a[j]=t;
                }
        }
        t=a[j];
        a[j]=a[pivot];
        a[pivot]=t;
        quicksort(a,left,j-1);
        quicksort(a,j+1,right);
        }
}
int main()
{
        int *a,n,i;
        printf("Enter no.of elements\n");
        scanf("%d",&n);
        a=(int *)malloc(n*sizeof(int));
        printf("Enter elements");
        for(i=0;i<n;i++)
        scanf("%d",&a[i]);
        quicksort(a,0,n-1);
        printf("After sorting\n");
        for(i=0;i<n;i++)
        printf("%d  ",a[i]);
}

No comments:

Post a Comment