快速排序

public class Main {

    public static void main(String[] args) {
        int [] a = { 9,8,7,6,15,4,3,2,1,5 } ;
        quickSort(a,0,a.length - 1);
        for (int i:a)
            System.out.println(i);
    }

    private static void quickSort(int [] a, int left, int right){
        if ( right - left <= 0)
            return ;
        else
        {
            int index = partition(a,left,right);
            quickSort(a,left,index - 1);
            quickSort(a,index + 1, right);
        }
    }

    private static int partition(int [] a, int left, int right) {
        int i = left, j = right - 1 ;
        int pivot = a[right];
        while(true)
        {
            while(i<= right && a[i]< pivot)
                i++ ;
            while(j>= left && a[j] > pivot )
                j-- ;

            if ( i >= j)
                break ;

            int temp = a[i];
            a[i] = a[j];
            a[j] = temp ;
        }

        a[right] = a[i];
        a[i] = pivot ;
        return i ;
    }
}

posted on 2010-07-08 00:05  sunliho  阅读(132)  评论(0编辑  收藏  举报