【发布时间】:2020-03-17 23:34:18
【问题描述】:
我正在尝试通过快速排序对这个数组进行排序:
int[] arr = {25,23,21,29,28,22,24,27};
我的快速排序功能:
public static void quickSort(int[] arr) { // sorts array using quick sort algorithm
if (arr[0] < arr[arr.length-1]) {
int s = hoarePartitioning(arr);
quickSort(Arrays.copyOfRange(arr, 0, s-1));
quickSort(Arrays.copyOfRange(arr, s+1, arr.length));
}
}
我使用了霍尔分区:
public static int hoarePartitioning(int[] arr) {
int pivot = arr[0];
int i = 0;
int j = arr.length;
do {
do {i++;} while(pivot >= arr[i] && i < arr.length);
do {j--;} while(pivot <= arr[j] && j >= 0);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}while(i <= j);
int temp = arr[i]; //undo last swap when i >= j
arr[i] = arr[j];
arr[j] = temp;
temp = arr[0];
arr[0] = arr[j];
arr[j] = temp;
return j;
}
但是,当我打印出数组时,结果如下:
22 23 21 24 25 28 29 27
我的 Hoare 分区功能工作正常,但我仍然不明白为什么数组没有排序。我在这里做错了什么? 谢谢。
【问题讨论】: