快速排序 java實現

這個先上代碼吧。 

複習了一遍。。發現各種不注意。思想還是轉一篇好的。

public class QuickSort {
    public static void main(String[] args){
        int[] a = {4,6,2,4,6,7,1,9};
        sort(a,0,a.length-1);
        for(int j : a){
            System.out.println(j);
        }
    }

    public static void sort(int[] a, int low , int high){
        if(low > high){
            return;
        }
        else {
            int partition = divide(a, low, high);
            sort(a, low, partition-1);
            sort(a, partition + 1 ,high);
        }
    }

    public static int divide(int[] a,int low, int high){
        int pivot;
        pivot = a[low];
        while(low < high){
            while(low < high && pivot <= a[high]) {
                high--;
            }
            if(low < high){
                int temp = a[high];
                a[high] = a[low];
                a[low] = temp;
                low++;
            }
            while(low < high && pivot >= a[low]){
                low ++ ;
            }
            if(low < high){
                int temp = a[low];
                a[low] = a[high];
                a[high] = temp;
                high--;
            }
        }
        return low; //返回low還是high 一樣。 因爲此時low = high
    }
}

点赞