快速排序


public class Demo {
    public static void main(String[] args) {
        int[] nums = {3,25,2,35};
        sort(nums,0,nums.length-1);

        for (int i : nums) {
            System.out.print(i+" ");
        }
    }

    public static void sort(int[]nums,int left,int right){
        int l = left;
        int r = right;
        //拿出左邊第一個數作爲起始點
        int povit = nums[l];

        while(l<r){

            while(l<r && nums[r] >= povit){
                //從右邊開始尋找,找到一個比起始點小的數
                r--;
            }

            if(l<r){
                //找到比起始點小的數,就交換位置
                int temp = nums[l];
                nums[l] = nums[r];
                nums[r] = temp;
                l++;
            }

            while(l<r && nums[l] <= povit){
                //從左邊開始找,找到一個比起始點大的數
                l++;
            }

            if(l<r){
                //找到比起始點大的是,就交換位置
                int temp = nums[l];
                nums[l] = nums[r];
                nums[r] = temp;
                r++;
            }
        }

        //遞歸
        if(l>left){ 
            sort(nums,left,l-1);
        }
        if(r<right){ 
            sort(nums,l+1,right);
        }

    }


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