2016-10-23 23 views
1

這裏公式化的算法的複雜度爲O(n^2)(插入排序)。該算法雖然得到NullPointerException,因爲String陣列中存在null元素。我如何讓我的算法使用空元素對數組進行排序?算法如下:使用InsertionSort算法對其中包含空元素的字符串Array進行排序

private void sortFlowers(String flowerPack[]) { 
    // TODO: Sort the flowers in the pack (No need to display 
    // them here) - Use Selection or Insertion sorts 
    // NOTE: Special care is needed when dealing with strings! 
    // research the compareTo() method with strings 

    String key; 

    for (int j = 1; j < flowerPack.length; j++) { //the condition has changed 
     key = flowerPack[j]; 
     int i = j - 1; 

     while (i >= 0) { 
      if (key.compareTo(flowerPack[i]) > 0) { //here too 
       break; 
      } 

      flowerPack[i + 1] = flowerPack[i]; 

      i--; 
     } 

     flowerPack[i + 1] = key; 
    } 
} 

回答

3

如果key可以爲空,那麼你就應該改變這種狀況:

key.compareTo(flowerPack[i]) > 0 

喜歡的東西:

compareKeys(key, flowerPack[i]) > 0 

,然後添加一個null -safe檢查,如:

private int compareKeys(final String first, final String second) { 
    if (first == null || second == null) { 
     return 0; // TODO: 0, here? 
    } else { 
     return first.compareTo(second); 
    } 
} 
1

compareTo()Comparable接口的一部分。它沒有用於將null與任何內容進行比較的定義行爲。它實際上不能有這種行爲,因爲a.compareTo(b)b.compareTo(a)需要一致。您可以:

1)實現自定義Comparator知道如何比較空,然後用myComparator.compare(key, flowerPack[i])

2)Not use nulls更換key.compareTo(flowerPack[i])

3),因爲這看起來像功課,重寫while往裏位只使用compareTo()如果keyflowerPace[i]非空。如果其中一個(或兩者)都爲空,則需要特殊情況。

相關問題