校招刷题群
高效刷题 迎战校招
校招精选试题
近年面笔经面经群内分享
Java刷题群 前端刷题群 产品运营群
首页 > 算法 > 高级排序(快排、堆排等)
题目

使用荷兰国旗思想优化快速排序代码。

解答

【解析】

在快速排序中可以使用荷兰国旗问题所采用的思想,即将每次划分的中间区域用来存放当前基数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public static void quickSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        quickSort(arr, 0, arr.length - 1);
    }
 
    public static void quickSort(int[] arr, int left, int right) {
        if (left < right) {
            //下面一句话就是为了避免当前的数组已经为完全有序或者反序的状态
            swap(arr, left + (int) (Math.random() * (right - left + 1)), right);
            int[] p = partition(arr, left, right);//返回等于基数的起始位置和结束位置
            quickSort(arr, left, p[0] - 1);
            quickSort(arr, p[1] + 1, right);
        }
    }
 
    public static int[] partition(int[] arr, int left, int right) {
        int less = left - 1;
        int more = right;
        while (left < more) {
            if (arr[left] < arr[right]) {
                swap(arr, ++less, left++);
            } else if (arr[left] > arr[right]) {
                swap(arr, --more, left);
            } else {//arr[left] == arr[right]
                left++;
            }
        }
        swap(arr, more, right);
        return new int[] { less + 1, more };
    }
 
    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
C 1条回复 评论
csdn

有知道笔记在哪下载的吗,跪求老师笔记

发表于 2023-10-02 22:00:00
0 0