The algorithm formulated here has a complexity of O(n^2) (insertion sort). The algorithm though gets a NullPointerException since there are null elements within the String array. How do I get my algorithm to sort an array with null elements? Algorithm below:
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;
}
}