Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, September 11, 2012

Quick Sort in JAVA

Quick Sort is one of the fastest sorting algorithms.
Here is the code snippet for Java.


public static int divide(int array[], int left, int right)
    {
        int i = left, j = right;
        int tmp;
        int pivot = array[(left + right) / 2];
       
        while (i <= j) {
            while (array[i] < pivot)
                i++;
            while (array[j] > pivot)
                j--;
            if (i <= j) {
                tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
                i++;
                j--;
            }
        }
        return i;
    }
    public static void q_srt(int arr[], int left, int right) {
        int i = divide(arr, left, right);
        if (left < i - 1)
            q_srt(arr, left, i - 1);
        if (i < right)
            q_srt(arr, i, right);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int []sample = {13,21,36,0,32,54,1,3};
        for(int x=0;x<sample.length;x++){
            System.out.print(sample[x]+":");
        }
        System.out.println("\n-=Sorted Array=-");
        q_srt(sample,0,7);
        for(int x=0;x<sample.length;x++){
            System.out.print(sample[x]+":");
        }
    }