Loading

LeetCode 912. 排序数组

image

思路

手撕快速排序。

class Solution {
    public int[] sortArray(int[] nums) {
        // 手撕快速排序
        int left = 0, right = nums.length-1;
        quickSort(nums, left, right);
        return nums;
    }

    public void quickSort(int[] nums, int left, int right) {
        if(left >= right) return;

        // 随机选一个数当主元,randIndex表示该随机主元的下标
        int randIndex = new Random().nextInt(right-left+1)+left;
        swap(nums, left, randIndex);
        int pivot = nums[left];
        int i = left, j = right;
        while(i != j) {
            while(i < j && nums[j] >= pivot) j--;
            while(i < j && nums[i] <= pivot) i++; 
            swap(nums, i, j);
        }

        swap(nums, left, i);
        quickSort(nums, left, i-1);
        quickSort(nums, i+1, right);
    }

    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
posted @ 2022-05-27 12:01  拾月凄辰  阅读(26)  评论(0编辑  收藏  举报