我有一个快速排序方法测试程序如下:
public class testtt {
public static void main(String[] args){
Integer[] list =new Integer[15];
list[0] =12;
list[1] = 28;
list[2] = 79;
list[3] = 19;
list[4] = 60;
list[5] = 22;
list[6] = 3;
list[7] = 50;
list[8] = 75;
list[9] = 60;
list[10] = 25;
list[11] = 97;
list[12] = 98;
list[13] = 12;
list[14] = 88;
quickSort(list,0,14);
for(int i=0;i<15;i++){
System.out.print(list[i]+"\t");
}
}
private static <E extends Comparable<E>> void quickSort(E[] list, int first, int last) {
if (last > first) {
int pivotIndex;
pivotIndex = partition3(list, first, last);
quickSort(list, first, pivotIndex - 1);
quickSort(list, pivotIndex + 1, last);
}
}
private static <E extends Comparable<E>> int partition3(E[] list, int first, int last) {
int pivotIndex = (first + last) / 2;
E pivot = list[pivotIndex]; // Choose the first element as the pivot
swap(list, last, pivotIndex);
pivotIndex = last;
last--;
do {
// Search forward from left
while (first < last && list[first].compareTo(pivot) <= 0)
first++;
// Search backward from right
while (first <= last && list[last].compareTo(pivot) > 0)
last--;
// Swap two elements in the list
if (last >= first) {
swap(list, first, last);
first++;
last--;
}
} while (last > first);
swap(list, pivotIndex, first);
return first;
}
private static <E> void swap(E[] list, int index1, int index2) {
E tmp = list[index1];
list[index1] = list[index2];
list[index2] = tmp;
}
}
正在运行的输出结果是
3 12 19 22 25 12 28 50 60 60 75 79 88 97 98
哪个没有排序......有人可以解释为什么这种方法出错了吗?我不需要正确版本的快速排序,我只是想知道为什么这个错误...我无法对python导师进行可视化或其他因为运行时间超过3秒......
答案 0 :(得分:0)
您必须从>
方法的do ... while循环中将>=
替换为partition
:
private static <E extends Comparable<E>> int partition3(E[] list, int first, int last) {
// Code
do {
// Code
} while (last >= first); <---------- Here
swap(list, pivotIndex, first);
return first;
}
如果必须在index[length/2]
中进行更改,则最终会发生这种情况,但未处理。
输出示例
Output : 0
[16, 40, 44, 60, 82, 5, 72, 63, 67, 89, 80, 31, 23, 44, 81]
[5, 16, 23, 31, 40, 44, 44, 60, 63, 67, 72, 80, 81, 82, 89]
Output : 1
[89, 28, 69, 77, 46, 79, 40, 66, 40, 4, 59, 9, 95, 92, 83]
[4, 9, 28, 40, 40, 46, 59, 66, 69, 77, 79, 83, 89, 92, 95]
Output : 2
[74, 54, 12, 42, 95, 29, 74, 76, 24, 18, 45, 37, 14, 87, 19]
[12, 14, 18, 19, 24, 29, 37, 42, 45, 54, 74, 74, 76, 87, 95]
Output : 3
[1, 48, 26, 42, 25, 79, 32, 31, 82, 65, 71, 43, 15, 26, 49]
[1, 15, 25, 26, 26, 31, 32, 42, 43, 48, 49, 65, 71, 79, 82]
Output : 4
[21, 6, 99, 30, 41, 93, 85, 10, 35, 67, 43, 4, 88, 62, 18]
[4, 6, 10, 18, 21, 30, 35, 41, 43, 62, 67, 85, 88, 93, 99]
Output : 5
[54, 62, 22, 22, 51, 71, 32, 17, 26, 19, 94, 61, 53, 82, 96]
[17, 19, 22, 22, 26, 32, 51, 53, 54, 61, 62, 71, 82, 94, 96]