算法训练营

1. 快速排序

public static void main(String[] args) {
        int[] nums = {-1,0,1,2,-1,-4};
        quickSort(nums, 0, nums.length - 1);
        Arrays.stream(nums).forEach(System.out::println);

    }

    public static void quickSort(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }
        //挖坑填数法 + 双指针
        int mid = nums[left];
        int i = left, j = right;
        while (i < j) {
            //从后往前找小于等于mid的数
            while (i < j && nums[j] > mid) {
                j--;
            }
            if (i < j) {
                nums[i] = nums[j];
                i++;
            }
            //从前往后找大于mid的数
            while (i < j && nums[i] <= mid) {
                i++;
            }
            if (i < j) {
                nums[j] = nums[i];
                j--;
            }
        }
        //i==j
        nums[i] = mid;
        //分而治之
        //左侧nums
        quickSort(nums, left, i - 1);
        //右侧nums
        quickSort(nums, i + 1, right);
    }

 

posted on 2022-07-11 14:22  -赶鸭子上架-  阅读(41)  评论(0编辑  收藏  举报