Java compareTo没有正确排序包含符号的字符串

时间:2017-11-10 21:45:15

标签: java algorithm sorting unicode

我有一个java程序,它构建一个最大堆,调用Heapify并对任何列表进行排序。目前,它将对字母表进行排序,没有任何问题,甚至是apple, addle, azzle之类的字符串列表也没有问题。下面是程序输入的屏幕截图,它包含在第一行排序的项目数,以及它下面的列表:

enter image description here

绿色输入我知道已经正确排序。如果您检查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) );
    }

}

忽略方法开头的条件,您可以看到我对字符串的比较只是使用java中的标准String.compareTo()进行的。为什么不能正确排序包含符号的字符串?请注意,我不需要自定义比较器,我只需要对字符串中包含的符号(键盘上的任何符号)进行unicode表示评估。 compareTo的javadoc读取:

  

按字典顺序比较两个字符串。比较基于字符串中每个字符的Unicode值。此String对象表示的字符序列按字典顺序与参数字符串表示的字符序列进行比较。如果此String对象按字典顺序位于参数字符串之前,则结果为负整数。如果此String对象按字典顺序跟随参数字符串,则结果为正整数。如果字符串相等,结果为零; compareTo恰好在equals(Object)方法返回true时返回0。

声明它使用unicode,对我的问题有任何建议吗?

测试文件(已排序):test.txt 代码文件:Main.javaMaxHeap.java

2 个答案:

答案 0 :(得分:2)

您正在使用compareToIgnoreCasejavadoc州:

  

此方法返回一个整数,其符号是调用compareTo的符号,其中字符串的规范化版本通过在每个字符上调用Character.toLowerCase(Character.toUpperCase(character))来消除大小写差异。

所以在你的例子中,']'和' n'确实在......之前。

答案 1 :(得分:2)

你没有使用compareTo(),你正在使用compareToIgnoreCase(),这解释了每个字符都被转换为大写,然后该字符被转换为小写。

您的字符串的第6个字母不同,分别为Yn]。在记录转换后,字符为yn]。因此,字符串按字典顺序排列为]nY

相关问题