這裏公式化的算法的複雜度爲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;
}
}