mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
269 字
1 分钟
【算法笔记】(六)随机快速排序
2026-01-13
统计加载中...
package org.example;
import java.io.*;
public class Main {
static int[] arr = {1 ,3, 2, 4, 1, 4, 6 ,2};
public static void main(String[] args) {
quickSort(0 ,arr.length - 1);
ArrUtil.printArr(arr);
}
public static void quickSort (int l ,int r) {
if (l >= r) {
return;
}
//随机抽取一个数组值,才能在概率上把我快速排序的时间复杂度收敛到n * logn
int x = arr[l + (int) (Math.random() * (r - l + 1))];
partition (l ,r ,x);
//为了防止底层的递归过程覆盖全局变量,用临时的变量记录first、last
int left = first;
int right = last;
quickSort(l ,left - 1);
quickSort(right + 1 ,r);
}
static int first;
static int last;
//已知数组在l到r的范围内一定有x这个值
//划分数组,<x的放左边,==x的放中间,>x的放右边
//把全局变量first,last更新为==x的左右边界
private static void partition(int l, int r, int x) {
first = l;
last = r;
int i = l;
while (i <= last) {
if (arr[i] == x) i ++;
else if (arr[i] < x) swap(first ++ ,i ++);
else swap(i ,last --);
}
}
private static void swap(int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
【算法笔记】(六)随机快速排序
http://hgqwd.icu/posts/suanfa6/
作者
天线宝宝死于谋杀
发布于
2026-01-13
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00