[英]Need assistance JAVA quicksort recursion
對於學校,我必須為數組數組編寫快速排序。 我認為我的分區很好,但是遞歸總是出錯。
public static int partition(String[] input, int max) {
// pivot is dividing point
// I keeps track of lesser values
// count is just a counter
// Pivots in place
int pivot = 0;
int i = 1;
int count = 1;
while (count <= max) {
if (input[count].compareTo(input[pivot]) < 0) {
input[i] = input[count];
i = i + 1;
}
if (count == max) {
input[i] = input[pivot];
input[pivot] = input[i];
}
count++;
}
return pivot;
}
public static void qSort(String[] input) {
int index = partition(input, input.length - 1);
int count = 0;
if (count < index - 1) {
partition(input, index - 1);
}
if (index + 1 < count && count < input.length) {
partition(input, input.length - 1);
}
count++;
}
您的實現有很多錯誤。 首先,您始終選擇軸作為要在數組索引0處的元素。 quicksort的思想是選擇一些樞軸,在其周圍對數組進行分區,然后在所選樞軸周圍的兩個分區上遞歸應用quicksort。 如何確定將遞歸調用quicksort的分區的開始和結束? 您需要像其他注釋中提到的那樣將那些參數作為參數傳遞給分區方法,對於quicksort方法本身也是如此。
public void swap (String [] array, int i, int j) {
String tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static int partition (String [] array, int low, int high) {
String pivot = array[low];
int index = low+1;
for (int i = low+1; i <= high; i++) {
if (pivot.compareTo(array[i]) > 0) {
swap(array, i, index);
index++;
}
}
swap(array, low, index-1);
return index-1;
}
public static void qsort(String [] array, int low, int high) {
if (low < high) {
int p = partition(array, low, high);
qsort(array, low, p);
qsort(array, p+1, high);
}
}
顯然,這不是選擇樞軸的最佳方法,因為某些數組會使算法的性能非常差。 更好的方法是每次使用隨機樞軸。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.