Linuxn00b Linuxn00b - 1 year ago 59
Java Question

Using an InsertionSort algorithm to sort an Array of Strings with null elements within them

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 NullElements. 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
flowerPack[i + 1] = flowerPack[i];
flowerPack[i + 1] = key;

Answer Source

If key can be null, then you should change this condition:

key.compareTo(flowerPack[i]) > 0

To something like:

compareKeys(key, flowerPack[i]) > 0

And then add a null-safe check, like:

private int compareKeys(final String first, final String second) {
    if (first == null || second == null) {
        return 0; // TODO: 0, here?
    } else {
        return first.compareTo(second);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download