开发者

Sorting an array alphabetically

I have an array which i need to sort its elements by occurrence then alphabetically. For example:

55 The
32 ASomething
32 BSomething

ASomething should come before Bsomething because:
1) they have the same number
2) A comes before B alphabeticall开发者_JAVA百科y

So you sort first by the number of occurrence then Alphabetically

What is the best way to do that. I am using merge sort to sort the counts but how do I put a statement that it will check if they have the same number, it sorts alphabetically (could be more than 2 words).

SOLUTION: What I did is a merge sort on the data before I did a merge sorts on the counts of data and that was good enough :) Thanks everyone for the help


You need a custom Comparator for that using 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));
  }
}

For Collections you can use Collections.sort()

The above assumes your array elements are Strings like "22 ASomething" rather than a specific data structure containing occurrences and some text. If that is the case you can use a simpler Comparator.

Also if you do have an array of Strings it might be worth first transforming it into an array of objects that have been parsed to save over-parsing the elements (ie some elements will be parsed more than once).


You should ensure that the sorting algorithm you are using guarantees "stability" as does java.util.Collections.sort:

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

You make no mention of what data structure you are using which would definitely guide your approach. For example, you might use a Map> to model your data in which case it would make sense to sort the Lists and then iterate through the ordered keys of the Map. This would not require a custom Comparator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜