2010-03-04 253 views
3

我有一個數組,我需要按照出現次序按字母排序其元素。 例如:按字母順序排列數組

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個單詞)的聲明。

SOLUTION:我所做的是在之前我做了數據的計數合併排序,那就是不夠好:)謝謝大家的幫助

+0

這不影響您如何處理計數,但是您的排序是否區分大小寫或不區分大小寫? – shoover 2010-03-04 00:49:05

+0

我的第一個想法是,哇,這在bash shell中會很容易。 :) – shoover 2010-03-04 00:49:23

+0

shoover:我使用java :) – user220755 2010-03-04 00:59:05

回答

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就像而不是包含事件和一些文本的特定數據結構。如果是這種情況,您可以使用更簡單的Comparator

此外,如果您確實有一個String的數組,它可能值得首先將其轉換爲已解析的對象數組以解救元素(即一些元素將被多次解析)。

0

您應該確保排序算法使用的是保證「穩定」一樣java.util.Collections.sort

此排序被保證是穩定的:等於元素將無法重新排序作爲排序的結果。

你沒有提到你正在使用哪種數據結構,這肯定會指導你的方法。例如,您可以使用Map>來爲數據建模,在這種情況下,對列表排序然後遍歷Map的排序鍵是有意義的。這不需要自定義比較器。

+0

爲什麼你認爲OP需要*穩定*排序? – 2010-03-04 07:49:41

+0

因爲OP有兩次排序「所以你先排序的次數然後按字母排序」 – msw 2010-03-04 15:59:27