快速排序(隨機生成pivot)


public class QuickSort {

    public static void main(String[] args) throws Exception {
        QuickSort quickSort = new QuickSort();
        int[] data = new int[]{1,2,1,1,0,-1};
        quickSort.QuickSort(data, 0, data.length - 1);
        System.out.println(Arrays.toString(data));
    }

    public void QuickSort(int[] data, int start, int end) throws Exception {
        if (start == end) {
            return;
        }
        int index = Partition(data, start, end);
        if (index > start) {
            QuickSort(data, start, index - 1);
        }
        if (index < end) {
            QuickSort(data, index + 1, end);
        }
    }


    private int Partition(int[] data, int start, int end) throws Exception {
        if (data == null || start < 0 || end >= data.length) {
            throw new Exception("輸入參數錯誤");
        }
        int partitionIndex = RandomInRange(start, end);
        int pivot = data[partitionIndex];
        // 將pivot和最後的元素交換,這樣比較的時候不會和pivot相比較,同時也讓最後一個元素參與了比較
        Swap(data, partitionIndex, end);
        int small = start - 1;
        for (int index = start; index < end; index++) {
            if (data[index] < pivot) {
                small++;
                if (small != index) {
                    Swap(data, small, index);
                }
            }
        }
        small++;
        // 將pivot移動到合適的位置
        Swap(data, small, end);
        return small; // 返回當前的劃分點的位置
    }


    private void Swap(int[] data, int index1, int index2) {
        int temp = data[index1];
        data[index1] = data[index2];
        data[index2] = temp;
    }

    /*隨機生成劃分的中心點*/
    private int RandomInRange(int start, int end) {
        Random random = new Random();
        // nextInt(n)生成的隨機數的範圍不包括n,所以我們下面加1。
        return random.nextInt(end - start + 1) + start;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章