71

我正在尝试使用compareTo(). 这是我的代码:

static String Array[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
String temp;

public static void main(String[] args)
{

   for (int j=0; j<Array.length;j++)
   {
       for (int i=j+1 ; i<Array.length; i++)
       {
           if (Array[i].compareTo(Array[j])<0)
           {
               String temp = Array[j];
               Array[j] = Array[i];
               Array[i] = temp;
           }
       }
       System.out.print(Array[j]);
   }
}

现在输出是:

Hello  This Example Sorting is

我得到了结果,但不是我想要得到的结果,它们是:

Hello This Example Is Sorting

如何调整我的代码以正确排序字符串数组?

4

8 回答 8

146

你的输出是正确的。表示开头的“Hello”和“This”的白色字符。

另一个问题是你的方法。使用Arrays.sort()方法:

String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);

输出:

 Hello
 This
Example
Is
Sorting

这里数组“is”的第三个元素应该是“Is”,否则排序后会排在最后。因为 sort 方法内部使用 ASCII 值对元素进行排序。

于 2012-10-20T07:43:26.920 回答
15

除了此处发布的替代解决方案(正确)之外,没有人通过解决您的代码有什么问题来真正回答您的问题。

好像您正在尝试实现选择排序算法。我不会在这里详细介绍排序的工作原理,但我提供了一些链接供您参考 =)

您的代码在语法上是正确的,但在逻辑上是错误的。您仅通过将每个字符串与其后面的字符串进行比较来对字符串进行部分排序。这是一个更正的版本(我保留了尽可能多的原始代码来说明它的“错误”):

static  String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String  temp;

//Keeps track of the smallest string's index
int  shortestStringIndex; 

public static void main(String[] args)  
{              

 //I reduced the upper bound from Array.length to (Array.length - 1)
 for(int j=0; j < Array.length - 1;j++)
 {
     shortestStringIndex = j;

     for (int i=j+1 ; i<Array.length; i++)
     {
         //We keep track of the index to the smallest string
         if(Array[i].trim().compareTo(Array[shortestStringIndex].trim())<0)
         {
             shortestStringIndex = i;  
         }
     }
     //We only swap with the smallest string
     if(shortestStringIndex != j)
     {
         String temp = Array[j];
         Array[j] = Array[shortestStringIndex]; 
         Array[shortestStringIndex] = temp;
     }
 }
}

延伸阅读

这种方法的问题在于它的渐近复杂度是O(n^2)。简而言之,随着数组大小的增长(接近无穷大),它变得非常慢。您可能想了解更好的数据排序方法,例如快速排序

于 2013-05-20T20:17:39.317 回答
10

我知道这是一个迟到的回复,但也许它可以帮助某人。

可以使用 trim() 函数删除空格。之后,如果您想以区分大小写的方式对数组进行排序,您可以使用:

Arrays.sort(yourArray);

对于不区分大小写的方式:

Arrays.sort(yourArray,String.CASE_INSENSITIVE_ORDER);

希望这可以帮助!

于 2015-09-11T11:35:35.867 回答
9

而不是这条线

if(Array[i].compareTo(Array[j])<0)

使用这条线

if(Array[i].trim().compareTo(Array[j].trim())<0)

你很高兴。其他用户已经解释了您当前代码不起作用的原因。上述替换是您可以应用的几种解决方法之一。

于 2012-10-20T08:07:38.903 回答
5

Java 8开始,如果您有包含大量元素的数组,您也可以使用parallelSortwhich 很有用。

例子:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "b", "y" };
    Arrays.parallelSort(strings);
    System.out.println(Arrays.toString(strings));   // [a, b, c, x, y]
}

如果要忽略大小写,可以使用:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "B", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.compareToIgnoreCase(o2);
        }
    });
    System.out.println(Arrays.toString(strings));   // [a, B, c, x, y]
}

否则B会在之前a

如果要在比较过程中忽略尾随空格,可以使用trim()

public static void main(String[] args) {
    String[] strings = { "x", "  a", "c ", " b", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.trim().compareTo(o2.trim());
        }
    });
    System.out.println(Arrays.toString(strings)); // [  a,  b, c , x, y]
}

于 2016-01-18T00:07:26.947 回答
4

" Hello " , " This " , "is ", "Sorting ", "Example"

首先,您在" Hello "and中提供了空格" This ",空格的值低于 Unicode 中的字母字符,因此它首先被打印。(其余字符按字母顺序排序)。

现在大写字母的值低于 Unicode 中的小写字母,因此打印“示例”和“排序”,然后最后打印"is "出最高值。

于 2013-08-19T17:05:17.073 回答
4

如果您使用:

if (Array[i].compareToIgnoreCase(Array[j]) < 0)

你会得到:

Example  Hello  is  Sorting  This

我认为这是您正在寻找的输出。

于 2015-03-02T12:01:30.457 回答
2

首先,您的问题是您使用了区分大小写的方法`compareTo()。这意味着大写字母与小写字母分开排序。原因是它翻译成 Unicode,其中大写字母的数字小于小写字母的数字。因此,您应该使用 `compareToIgnoreCase()`,就像之前的帖子中提到的那样。

这是我如何有效地做到这一点的完整示例方法

创建Comparator的对象后,您可以在java.util.Arrays 中定义的这个版本的 `sort()` 中传递它。

static<T>void sort(T[]array,Comparator<?super T>comp)

仔细看看超级。这确保了传入的数组与比较器的类型是可对抗的。

这种方式的神奇之处在于,您可以轻松地以相反的顺序对字符串数组进行排序,您可以通过以下方式轻松完成:

return strB.compareToIgnoreCase(strA);

import java.util.Comparator;

    public class IgnoreCaseComp implements Comparator<String> {

        @Override
        public int compare(String strA, String strB) {
            return strA.compareToIgnoreCase(strB);
        }

    }

  import java.util.Arrays;

    public class IgnoreCaseSort {

        public static void main(String[] args) {
            String strs[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
            System.out.print("Initial order: ");

            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");

            IgnoreCaseComp icc = new IgnoreCaseComp();

            Arrays.sort(strs, icc);

            System.out.print("Case-insesitive sorted order:  ");
            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");

            Arrays.sort(strs);

            System.out.print("Default, case-sensitive sorted order: ");
            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");
        }

    }

 run:
    Initial order:  Hello   This  is  Sorting  Example 

    Case-insesitive sorted order:   Hello   This  Example is  Sorting  

    Default, case-sensitive sorted order:  Hello   This  Example Sorting  is  

    BUILD SUCCESSFUL (total time: 0 seconds)

另类选择

该方法compareToIgnoreCase()虽然适用于很多场合(就像比较英语中的字符串),但它不适用于所有语言和位置。这自动使其成为不适合使用的选择。为确保在您应该使用 java.text.Collat​​or 的任何地方都compare()支持

您可以通过调用方法找到您所在位置的整理器getInstance()。之后,您应该设置此 Collat​​or 的强度属性。这可以通过setStrength()方法和Collator.PRIMARY作为参数来完成。有了这个替代选择,IgnocaseComp可以像下面那样编写。此版本的代码将独立于位置生成相同的输出

import java.text.Collator;
import java.util.Comparator;

//this comparator uses one Collator to determine 
//the right sort usage with no sensitive type 
//of the 2 given strings
public class IgnoreCaseComp implements Comparator<String> {

    Collator col;

    IgnoreCaseComp() {
        //default locale
        col = Collator.getInstance();

        //this will consider only PRIMARY difference ("a" vs "b")
        col.setStrength(Collator.PRIMARY);
    }

    @Override
    public int compare(String strA, String strB) {
        return col.compare(strA, strB);
    }

}
于 2017-05-24T12:23:02.530 回答