算法-快速排序

详细思路直接看我录制的视频吧 算法-快速排序_哔哩哔哩_bilibili

class Solution {
    // 快速排序
    public int[] sortArray(int[] nums) {
        if (nums == null || nums.length == 1) {
            return nums;
        }
        sort(nums, 0, nums.length - 1);
        return nums;
    }

    private void sort(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = findMid(nums, left, right);
        sort(nums, left, mid-1);
        sort(nums, mid + 1, right);
    }

    private int findMid(int[] nums, int left, int right) {
        int key = left;
        int value = nums[left];
        while (left < right) {
            while (left < right && nums[right] >= value) {
                right--;
            }
            while (left < right && nums[left] <= value) {
                left++;
            }
            swip(nums, left, right);
        }
        swip(nums, key, left);
        return left;
    }

    private void swip(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}

你可能感兴趣的:(算法,排序算法,数据结构,java,leetcode)