Sunday 6 January 2013

PROGRAM FOR QUICK SORT IN JAVA


import java.io.*;

class Quick

{

        public static void main ( String args[] )

        throws IOException

        {

                BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) );

                System.out.print("\n\nEnter size of Array : ");

                int n = Integer.parseInt ( br.readLine () );

                int a[] = new int[n];

                System.out.println("\n\nEnter array elements -\n ");

                for ( int i=0 ; i<n ; i++ )

                {

                        System.out.print("\na[" + i + "] = ");

                        a[i] = Integer.parseInt( br.readLine() );

                }

                sort ( a , 0 , n-1 );

                System.out.println("\n\nSorted Array -\n");

                for ( int i=0 ; i<n ; i++ )

                {

                        System.out.print("\na[" + i + "] = ");

                        System.out.println(a[i]);

                }

                System.out.println();

        }

        public static void sort ( int a[] , int l , int h )

        {

                int low,high,key,tmp;

                low = l;

                high = h;

                key = a[ ( low + high ) / 2 ];

                do

                {

                        while ( key > a[low] )

                        {

                                low++;

                        }

                        while ( key < a[high] )

                        {

                                high--;

                        }

                        if ( low <= high )

                        {

                                tmp = a[low];

                                a[low++] = a[high];

                                a[high--] = tmp;

                        }

                } while ( low <= high );

                if ( l < high )

                        sort ( a , l , high );

                if ( low < h )

                        sort ( a, low , h );

        }

}

No comments: