现在的位置: 首页 > 综合 > 正文

快速排序(书中例子实现)

2013年10月10日 ⁄ 综合 ⁄ 共 733字 ⁄ 字号 评论关闭
/*
2011-9-18
author:BearFly1990
*/
package algorithm;

import java.util.Arrays;

public class QuickSort {
    public static void main(String[] args) {
        int[] a = new int[] {5, 9, 8, 4, 7, 3, 6, 2};
        System.out.println(Arrays.toString(a));
        sort(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a));
    }

    private static void sort(int[] a, int low, int high) {
        if(low >= high)return;
        if(high - low == 1){
            if(a[0] > a[1])
                swap(a,0,1);
            return ;
        }
        int pivot = a[low];
        int left = low + 1;
        int right = high;
        while(left < right){
            while(left < right && left <= high){
                if(a[left] > pivot)break;
                left++;
            }
            while(left <= right && right > low){
                if(a[right] <= pivot)
                    break;
                right--;
            }
            if(left < right)swap(a,right,left);
        }
        swap(a,low,right);
        sort(a,low,right);
        sort(a,right + 1, high);
    }

    private static void swap(int[] a, int i, int j) {
        int temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

抱歉!评论已关闭.