编程语言
首页 > 编程语言> > 算法训练营

算法训练营

作者:互联网

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);
    }

 

标签:right,nums,int,训练营,mid,while,算法,left
来源: https://www.cnblogs.com/hello-yz/p/16466278.html