0

Here is the merge method of my merge sort algorithm

private void merge(T[] data, int first, int last) {
temp = new Comparable[data.length] ;
        int mid  = (first+last) /2 ;
        int it1 = 0 ;
        int it2 = first ;
        int it3 = mid + 1 ;
        System.out.println("mid = " + mid + " length = " + data.length);//for testing purposes

        while(it2 <= mid && it3 < data.length)
        {
            System.out.println("it2 = " + it2 +" it3 = "+ it3);//for testing purposes
            if(data[it2].compareTo(data[it3]) < 0)
                temp[it1++] = data[it2++] ;
            else
                temp[it1++] = data[it3++] ; 
        }

        while(it2 <= mid)
            temp[it1++] = data[it2++] ; 

        while(it3 < data.length)
            temp[it1++] = data[it3++];  

        for (int i = 0; i < data.length; i++) 
            data[i] = (T) temp[i] ;

But I keep on receiving a java.lang.Integer.compareTo(Unknown Source) error when this merge method is called. I am not sure how I am getting this error at the data[it2].compareTo(data[it3]) line because the while loop ensures both it2 and it3 dont go out of bounds.

Thanks

Keaton Pennells
  • 189
  • 2
  • 4
  • 15
  • If `it2` or `it3` had gone out of bounds, you'd have received an `ArrayIndexoutOfBoundsException`, but you said you're getting a `NullPointerException`, which means that your `data` array contains null values. – Andreas May 20 '16 at 04:05
  • What is contained in your `data` array? May be there is an object which is null or which is not an integer? – Vishal May 20 '16 at 04:09
  • `new Comparable` ? Comparable is an interface. You cannot instantiate an interface. This code would give compilation error first of all. – Saurav Sahu May 20 '16 at 04:14
  • No, it does not give compile error. `new Comparable[]` does not instantiate an interface. It instantiates an array whose items must implement the interface, there is nothing wrong with that. – T. Claverie May 20 '16 at 04:37

0 Answers0