Mitchell Gray Edwards
Mitchell Gray Edwards

Reputation: 57

Insertion Sort Function

This insertion sort function is supposed to take in an array of Drink objects and sort them according to one of their properties (cost). This property is fetched by getCost(). I keep getting a NullPointer error. The code is as follows:

    public void sortDrinks(Drink[] drinks){
    for(int i = 1; i <= drinks.length; i++){
        Drink key = drinks[i];
        int count = i-1;
        while((count >= -1)&&(drinks[count].getCost() > key.getCost())){
            drinks[count+1] = drinks[count];
            count--;
        }

        drinks[count+1] = key;
    }

}

Upvotes: 1

Views: 85

Answers (2)

cassm
cassm

Reputation: 203

When count is equal to -1, you are trying to access the getcost method of drinks[-1]. I believe this will be fixed if you change "while count >= -1" to "while count > -1".

This will obviously require a small amount of restructuring, for the drink to then be inserted in the correct place.

Upvotes: 1

Malik Brahimi
Malik Brahimi

Reputation: 16711

Why not implement the comparable interface in your Drink class?

public class Drink implements Comparable<Drink> {

    // attributes and constructor

    public int getCost() {
        return cost;
    }

    public int compareTo(Drink other) {
        return getCost().compareTo(other.getCost());
    }
}

Then later on you can sort the array of Drink objects that is passed with:

Collections.sort(drinks); // returns the sorted drinks

Upvotes: 1

Related Questions