Quick Sort

2016-12-02  本文已影响0人  无为无悔
public class Solution {

    public void quickSort(int[] arr, int left, int right) {
        int pivotIndex = partition(arr, left, right);
        if(left < pivotIndex - 1)
            quickSort(arr, left, pivotIndex - 1);
        if(right > pivotIndex)
            quickSort(arr, pivotIndex, right);
    }

    public int partition(int[] arr, int left, int right) {
        int pivot = arr[(left+right)/2];
        while(left <= right) {
            while(arr[left] < pivot)
                ++ left;
            while(arr[right] > pivot)
                -- right;
            if(left <= right) {
                swap(arr, left, right);
                ++ left;
                -- right;
            }
        }
        return left;
    }

    public void swap(int[] arr, int a, int b) {
        int tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
    }
}

上一篇 下一篇

猜你喜欢

热点阅读