写个快排的java代码
时间: 2023-06-01 15:05:38 浏览: 41
public static void quickSort(int[] arr, int low, int high) {
if (arr == null || arr.length == 0)
return;
if (low >= high)
return;
// 选定基准元素,以此为分界点
int middle = low + (high - low) / 2;
int pivot = arr[middle];
// 将大于基准元素的放到右边,小于基准元素的放到左边
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
// 递归排序子序列
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}
阅读全文