我在做什么错误的,我下面的quicksort实现:快速排序执行错误的java
public static void quicksort(int[] array, int start, int end) {
while (start < end) {
int pIndex = partition(array, start, end);
quicksort(array, start, pIndex - 1);
quicksort(array, pIndex + 1, end);
}
}
public static int partition(int[] array, int start, int end) {
int pivot = array[end];
int pIndex = start;
for (int i = start; i <= end - 1; i++) {
if (array[i] <= pivot) {
int tmp = array[pIndex]; // swap values
array[pIndex] = array[i];
array[i] = tmp;
pIndex++;
}
}
int tmpVal = array[pIndex];
array[pIndex] = pivot;
array[end] = tmpVal;
return pIndex;
}
当运行此针对数组{的测试用例7,5,3,6,8,1,2, 4},它将数组重新排列为{1,2,3,4,8,5,7,6},在那里它排列数组的左边,然后输入似乎是无限循环的数组{ 1,2}并且永不离开递归调用。我已经尝试添加一个基本的情况下,如果array.length小于2,然后返回;但这没有什么区别。
这是我的code的链接。
任何人都知道什么可能是错的?
是我们必然要使用现有的代码,或者我们可以把它扔掉,并开始了新的? –
我现有的代码,因为我们试图调试这个实现XD – OpMt