[數據結構]快排Java 實現 記錄

import java.util.Random;

public class QuickSort {
    public void quickSort(int[] nums, int start, int end) throws Exception {
        if(nums==null) throw new Exception("空指針");
        if(nums.length==0||end<start|| start<0||end>=nums.length) throw new Exception("下標越界");

        if (start==end) return;

        int index = partition(nums, start, end);

        if(index>start)
            quickSort(nums, start,index-1);

        if(index<end)
            quickSort(nums, index+1, end);
    }

    public int partition(int[] nums, int start, int end){
        // 隨機選擇一個數 放在末尾 選擇這個數做爲pivot
        Random random = new Random();
        int index = random.nextInt(end-start+1) + start;
        swap(nums, index, end);

        int small_board = start-1; // j 始終指向小於pivot的數字的區間的最右側
        for(int i =start; i<end;i++){
            if(nums[i]<nums[end]){
                small_board++;
                // 只有新邊界不等於遊標i 的時候才交換,減小沒必要要的交換
                if(small_board!=i) 
                    swap(nums, i, small_board);
            }
        }

        ++small_board;
        swap(nums, small_board, end);
        return small_board;
    }

    private void swap(int[] nums, int i, int j){
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }

//    public static void main(String[] args) throws Exception {
//        int[] nums = {1,2,3};
//        quickSort(nums,0, nums.length-1);
//        for(int k: nums) System.out.print(k + "\t");
//    }
}
相關文章
相關標籤/搜索