按字母顺序排序数组

时间:2010-03-04 00:43:25

标签: java

我有一个数组,我需要按字母顺序对其元素进行排序。 例如:

55 The
32 ASomething
32 BSomething

ASomething should come before Bsomething because:
1) they have the same number
2) A comes before B alphabetically

因此,您首先按出现次数按字母顺序排序

最好的方法是什么? 我使用合并排序来对计数进行排序,但是我如何设置一个声明,它将检查它们是否具有相同的数字,它按字母顺序排序(可能超过2个单词)。

解决方案:我做的是在对数据进行合并排序之前对数据进行合并排序,这非常好:)感谢大家的帮助

2 个答案:

答案 0 :(得分:4)

您需要使用Comparator自定义Arrays.sort()

Arrays.sort(array, new CustomComparator());

public class CustomComparator implements Comparator<String> {
  private final Pattern pattern = Pattern.compile("(\\d+)\\s+(.*)");

  public int compare(String s1, String s2) {
    Matcher m1 = pattern.matcher(s1);
    if (!m1.matches()) {
      throw new IllegalArgumentException("s1 doesn't match: " + s1);
    }
    Matcher m2 = pattern.matcher(s2);
    if (!m2.matches()) {
      throw new IllegalArgumentException("s2 doesn't match: " + s2);
    }
    int i1 = Integer.parseInt(m1.group(1));
    int i2 = Integer.parseInt(m2.group(1));
    if (i1 < i2) {
      return 1;
    } else if (i1 > i2) {
      return -1;
    }
    return m1.group(2).compareTo(m2.group(2));
  }
}

对于Collections,您可以使用Collections.sort()

以上假设您的数组元素String"22 ASomething"类似,而不是包含出现次数和某些文本的特定数据结构。如果是这种情况,您可以使用更简单的Comparator

此外,如果你有一个String数组,可能需要先将它转换为一个已被解析的对象数组,以保存过度解析元素(即一些元素将被解析多次)。

答案 1 :(得分:0)

您应该确保您使用的排序算法与java.util.Collections.sort一样保证“稳定性”:

  

这种保证是稳定的:相同的元素不会因排序而重新排序。

您没有提及您使用的数据结构,这肯定会指导您的方法。例如,您可以使用Map&gt;为数据建模,在这种情况下,对列表进行排序然后迭代Map的有序键是有意义的。这不需要自定义Comparator。

相关问题