我手动实现了快速排序算法。这是我的代码。下面的代码是无限运行:
public class QuickSort {
private static int partition(int[] arr, int low, int high) {
int pivot = (low + high) / 2;
int pivotValue = arr[pivot];
while (low <= high) {
while (arr[low] < pivotValue) {
low++;
}
while (arr[high] > pivotValue) {
high--;
}
if (low <= high) {
int tmp = arr[low];
arr[low] = arr[high];
arr[high] = tmp;
low++;
high--;
}
}
return low;
}
private static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void quicksort(int[] arr, int low, int high) {
if (low >= high) return;
int k = partition(arr, low, high);
quicksort(arr, low, k);
quicksort(arr, k+1, high);
}
public static void quicksort(int[] arr) {
quicksort(arr, 0, arr.length - 1);
}
public static void main(String[] args) {
// int[] arr = new int[]{9, 2, 3, 4, 1, 8, 7};
int[] arr = new int[]{1, 2, 5, 4, -1, -2, -3};
quicksort(arr);
print(arr);
}
}
错误的是:
int k = partition(arr, low, high);
quicksort(arr, low, k);
quicksort(arr, k+1, high);
如果我再次更新:
int k = partition(arr, low, high);
quicksort(arr, low, k-1);
quicksort(arr, k, high);
我不明白这一点。为什么某些实现看到这个可以互换。意味着我可以使用这两种情况。但第一个让我无限循环。
由于
答案 0 :(得分:0)
确保调试可以提供帮助,但我猜问题是在
的情况下low == hight + 1 =>
pivot == low =>
return low == hight =>
下一次调用quicksort(arr,low,k)将再次调用partition(arr,low,high);