Friday 25 October 2013

QuickSort

import java.io.*;
class QuickSort
{
    int p,l,r;
    void qs(int item[],int left,int right)
    {
        l=left;
        r=right;
        p=item[left];
        while(left<right)
        {
            while((item[right]>=p)&&(left<right))
            right--;
            if(left!=right)
            {
                item[left]=item[right];
                left++;
            }
            while((item[left]<=p)&&(left<right))
            left++;
            if(left!=right)
            {
                item[right]=item[left];
                right--;
            }
        }
        item[left]=p;
        p=left;
        left=l;
        right=r;
        if(left<p)
        qs(item,left,p-1);
        if(right>p)
        qs(item,p+1,right);
    }
    public static void main(String arg[])throws IOException
    {
        int a[];
        QuickSort ob=new QuickSort();
        BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter no. of elements of array A");
        int l=Integer.parseInt(x.readLine());
        a=new int[l];
        System.out.println("Enter elements of array A");
        for(int i=0;i<l;i++)
        a[i]=Integer.parseInt(x.readLine());
        System.out.println("Array elements of A");
        for(int i=0;i<l;i++)
        System.out.print(a[i]+" ");
        System.out.println("\nArray elements of A after sorting");
        ob.qs(a,0,l-1);
        for(int i=0;i<l;i++)
        System.out.print(a[i]+" ");
    }
}

No comments:

Post a Comment