快速排序

2021-05-02 10:27

阅读:601

标签:sort   dom   div   code   swap   一个   exti   int   array   

对一个数组按照快速排序方式排序:

public class Solution {
public int[] sortArray(int[] nums) {
        int len = nums.length;
        quickSort(nums, 0, len - 1);
        return nums;
    }

    private void quickSort(int[] nums, int left, int right) {
        int pIndex = partition(nums, left, right);
        quickSort(nums, left, pIndex - 1);
        quickSort(nums, pIndex + 1, right);
    }
    
    private int partition(int[] nums, int left, int right) {
        int randomIndex = RANDOM.nextInt(right - left + 1) + left;
        swap(nums, left, randomIndex);

        // 基准值
        int pivot = nums[left];
        int lt = left;
        
        for (int i = left + 1; i ) {
            if (nums[i]  pivot) {
                lt++;
                swap(nums, i, lt);
            }
        }
        swap(nums, left, lt);
        return lt;
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}

 

快速排序

标签:sort   dom   div   code   swap   一个   exti   int   array   

原文地址:https://www.cnblogs.com/liang1101/p/13204288.html


评论


亲,登录后才可以留言!