[英]bug in java quicksort algorithm implementation
不知何故,我輸入的最后一個元素未與我要提供給quicksort方法的列表進行排序
例如
輸入:5,7,3,2,7,8,9,0,3,1,2,3
結果:0 1 2 2 3 3 5 7 7 8 9 3
輸入:5,4,2,12,9,4
結果:2 4 5 9 12 4
任何想法,我要去哪里錯了?
public class QuickSort2 {
private static void quickSort(int[] list) {
quickSort(list, 0, list.length - 1);
}
private static void quickSort(int[] list, int p, int q) {
if (p < q) {
int pivotIndex = partition(list, p, q);
quickSort(list, p, pivotIndex - 1);
quickSort(list, pivotIndex + 1, q);
}
}
private static int partition(int[] list, int p, int q) {
int x = list[p];
int i = p;
int temp, temp2;
for (int j = p + 1; j < list.length - 1; j++) {
if (list[j] < x) {
i = i + 1;
// exchange list[i] with list[j]
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// exchange list[p] with list[i]
temp2 = list[p];
list[p] = list[i];
list[i] = temp2;
return i;
}
}
編輯
public class QuickSort2 {
private static void quickSort(int[] list) {
quickSort(list, 0, list.length - 1);
}
private static void quickSort(int[] list, int p, int q) {
if (p < q) {
int pivotIndex = partition(list, p, q);
quickSort(list, p, pivotIndex - 1);
quickSort(list, pivotIndex + 1, q);
}
}
private static int partition(int[] list, int p, int q) {
int x = list[p];
int i = p;
int temp, temp2;
for (int j = p + 1; j <= q; j++) {
if (list[j] < x) {
i = i + 1;
// exchange list[i] with list[j]
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// exchange list[p] with list[i]
temp2 = list[p];
list[p] = list[i];
list[i] = temp2;
return i;
}
}
您的for
循環“跳過”最后一個元素:
for (int j = p + 1; j < list.length - 1; j++)
像這樣修改它:
for (int j = p + 1; j < list.length; j++)
順便說一句,它不應該是list.length
因為那樣您就可以做不必要的工作。 您應該在[p..q]
(包括兩個端點)范圍內工作,而不是在整個數組上工作,所以這足夠了:
for (int j = p + 1; j <= q; j++)
您的實現(即使可行)看起來很不典型。 看一下Quicksort 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.