快速排序的使用

65 阅读1分钟

1、给你一个整数数组 nums,请你将该数组升序排列。 思路:快排利用了分治的思想,通过每一轮把数组分成2部分,选取中间元素为基准,小于基准元素的换到左边,大于基准元素的换到右边。

class Solution {
    
    public int[] sortArray(int[] nums) {
        if(nums == null || nums.length <=1 ) return nums;
        quickSort(nums, 0, nums.length-1);
        return nums;
    }
    //quickSort方法通过递归的方式实现了分治
    public void quickSort(int[] nums, int start, int end){
        if(start < end){
            int pivot = partition(nums, start, end);
            quickSort(nums, start, pivot - 1);
            quickSort(nums, pivot +1, end);
        }
    }
    //partition方法里用左右指针实现元素交换。
    public int partition(int[] nums, int lo, int hi){
        int pivot = nums[lo];
        while(lo < hi){
            while(nums[hi] > pivot && hi >lo) {hi--;}
            nums[lo] = nums[hi];
            while(nums[lo] <= pivot && hi >lo) {lo++;}
            nums[hi] = nums[lo];
        }
        nums[lo] = pivot;
        return lo;
    }
}