我有一個java程序,它構建一個最大堆,調用Heapify並對任何列表進行排序。目前它將排序字母沒有問題,甚至像apple, addle, azzle
這樣的字符串列表沒有問題。下面是輸入的截圖程序,這需要項目的數量在第一線進行梳理,並在它下面的列表:Java比較要正確排序包含符號的字符串
綠色是輸入,我知道已經正確排序。如果您檢查unicode table,則可以看到綠色列表已正確排序。但是我的程序輸出不正確(白色)。
下面是我的Heapify()的代碼片段:
//takes the maxheap(array) and begins sorting starting with the root node
public void Heapify(String[] A, int i)
{
if(i > (max_size - 2))
{
System.out.println("\nHeapify exceeded, here are the values:");
System.out.println("max_size = " + max_size);
System.out.println("i = " + i);
return;
}
//if the l-child or r-child is going to exceed array, stop
if((2 * i) > max_size || ((2 * i) + 1) > max_size)
return;
String leftChild = getChild("l", i); //get left child value
String rightChild = getChild("r", i); //get right child value
if ( (A[i].compareTo(leftChild) > 0) && (A[i].compareTo(rightChild) > 0) )
return; //i node is greater than its left and right child node, Heapify is done
//if left is greater than right, switch the current and left node
if(leftChild.compareTo(rightChild) > 0)
{
//Swap i and left child
Swap(i, (2 * i));
Heapify(this.h, (2 * i));
} else {
//Swap i and right child
Swap(i, ((2 * i) + 1));
Heapify(this.h, ((2 * i) + 1));
}
}
忽略的方法開始的情況下,你可以看到我的字符串的比較簡單的發生與標準String.compareTo()
在Java 。爲什麼不能正確地對包含符號的字符串進行排序?請注意,我不需要自定義比較器,我只需要包含在字符串中的符號(鍵盤上的任何符號)就可以用它們的unicode表示進行評估。用於compareTo
的javadoc的內容如下:
按字母順序比較兩個字符串。該比較基於字符串中每個字符的Unicode值。由該String對象表示的字符序列按字典順序與參數字符串表示的字符序列進行比較。如果此String對象按照字典順序排列在參數字符串之前,那麼結果爲負整數。如果此String對象按照字典順序跟隨參數字符串,則結果爲正整數。如果字符串相等,結果爲零;當equals(Object)方法返回true時,compareTo返回0。
說明它使用unicode,對我的問題有什麼建議嗎?
測試文件(已排序):test.txt 代碼文件:Main.java,MaxHeap.java
請爲你的「-1」提交一個評論,說明你爲什麼低估這個問題,而不是做一個「驅動器downvote」 – Chisx