import java.util.Arrays;
//快速排序
public class QuickSort {
public static void main(String[] args) {
int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int left, int right) {
int l = left;//左下标
int r = right;//右下标
int pivot = arr[(left + right) / 2]; //中间值
int temp = 0;
while (l < r) {//让比pivot中间值小的放到pivot左边,比pivot值大的放到右边
while (arr[l] < pivot) {//在pivot左边一直找,直到找到大于或等于pivot值,退出
l += 1;
}
while (arr[r] > pivot) {//在pivot左右边一直找,直到找到小于或等于pivot值,退出
r -= 1;
}
if (l >= r) {//如果成立,说明pivot俩边的值已经按照左边全部是小于等于pivot的值,右边全部是大于等于pivot的值
break;
}
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
//如果交换后,发现arr[l]==pivot,前移
if (arr[l] == pivot) {
r -= 1;
}
//如果交换后,发现arr[l]==pivot,前移
if (arr[r] == pivot) {
l += 1;
}
}
//如果l==r,必须l++,r--,否则出现栈溢出
if (l == r) {
l += 1;
r -= 1;
}
if (left < r) {//左递归
quickSort(arr, left, r);
}
if (right > l) {
quickSort(arr, l, right);
}
}
}
数据结构-快速排序
于 2020-08-06 20:13:34 首次发布