我有一个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