Search code examples
javaarrayssortingcomparetoinsertion

Applying insertion sort to arrays of objects


I'm trying to apply insertion sort to an array of objects but my else if never compiles and says "bad operand types".

Just wondering if I need to make a very specific compareTo method or if there's a better way of comparing arrays of objects in an insertion sort method.

EDIT:

So here's me trying to use my compareTo method and it compiles but I get a null pointer exception on the else if. Why?

public static void insertElement(WordClass[] Words, int next)
{
    WordClass value = Words[next];
    int i = next;

    while(true)
    {
        //
        if(i == 0)
        {
            Words[0] = value;
            break;
        }

        else if(Words[i-1].getStr().compareTo(value.getStr()) <= 0)
        {
            Words[i] = value;
            break;
        }
        else
        {
            Words[i] = Words[i-1];
            i--;
        }
    }
}


public static void insertionSort(WordClass[] Words)
{
    for(int i = 1; i< Words.length; i++)
    {
        insertElement(Words, i);
    }
}

     //in WordClass
     public int compareTo(WordClass w) //makes WordClass comparable
{
    return getStr().compareTo(w.getStr()); 

}

Solution

  • You should always use campareTo instead of == or <= operators for object types, unless you want to campare two object variables to see if both refers to same object. Also your WordClass class must implement the Camparable interface in order for this to work.