Saturday, 15 December 2012

Write Java Program to implement Quick Sort.


This Sorting Algorithm is based on Divide and Conquer approach.

package quicksort;
public class QuickSort {

    public static void main(String[ ] args) {
        int [ ]A = {6, 9, 18, 4, 3, 15};
        Sort qs = new Sort();
        qs.sort(A,0,A.length-1);
        qs.print(A);
       
    }
   
}
class Sort
{
    void sort(int [ ]A, int p, int r)
    {
        int q = 0;
        if(p<r)
        {
            q = this.partition(A, p, r);
            sort(A,p, q -1);
            sort(A,q+1,r);
        }
    }
    int partition(int [ ]A,int a, int b)
    {
        int x =A[b];
        int i = a -1;
         for (int j = a;j<=b -1; j++)
         {
             if(A[j]<=x)
             {
                 i++;
                 //Swap
                 if(A[i]!=A[j])
                 {
                    A[i] = A[i] ^ A[j];
                    A[j] = A[i] ^ A[j];
                    A[i] = A[i] ^ A[j];
                 }
             }
                      }
         A[i+1] = A[i+1] ^ A[b];
         A[b] = A[i+1] ^ A[b];
         A[i+1] = A[i+1] ^ A[b];
         return i+1;
   
    }
    void print(int [ ]A)
         {
             System.out.println();
             for(int i=0;i<A.length;i++)
             {
                 if(i!=A.length-1)
                     System.out.print(A[i]+ ",");
                 else
                     System.out.print(A[i]);;
             }
         }
}

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top