我創建了以下類來排序字符串數組。Java - 我的排序不起作用
public class StringSort {
private String[] hotelNames;
private int arrayLength;
public void sortHotel(String[] hotelArray) {
if (hotelArray.length <= 1) {
return;
}
this.hotelNames = hotelArray;
arrayLength = hotelArray.length;
quicksort(0, arrayLength - 1);
}
private void quicksort(int low, int high) {
int i = low, j = high;
String first = hotelNames[low];
String last = hotelNames[high];
String pivot = hotelNames[low + (high - low)/2];
while((first.compareTo(last)) < 0) { // first is less than last
while((hotelNames[i].compareTo(pivot)) < 0) { // ith element is < pivot
i++;
}
while((hotelNames[j].compareTo(pivot)) > 0) { // jth element is > pivot
j--;
}
if ((hotelNames[i].compareTo(hotelNames[j])) <= 0) {
swap(i, j);
i++;
j--;
}
//recursive calls
if (low < j) {
quicksort(low, j);
}
if (i < high) {
quicksort(i, high);
}
}
}
private void swap(int i, int j) {
String temp = hotelNames[i];
hotelNames[i] = hotelNames[j];
hotelNames[j] = temp;
}
}
然而,在我的主類(一類測試StringSort),當我做:
StringSort str = new StringSort();
String[] hotel1 = {"zzzz", "wwww", "dddd", "bbbbb", "bbbba", "aaaf", "aaag", "zzz"};
str.sortHotel(hotel1);
然後我有打印出數組的另一種方法。但是,當它打印出來時,它將原樣輸出hotel1數組,保持不變。沒有「排序」發生,我不確定我出錯的地方。
你做了什麼調試?將打印輸出添加到swap()並查看它是否在執行您期望的交換。 –
沒有調試抱歉,仍然在學習這樣做。 – Khalid
我認爲compareTo比較合適,因爲它比較字符串的字典順序。 – Khalid