Search code examples
javadebuggingheapheapsort

heap sort implementation bug, with the insert function


I need to implement something with a heap sort, and I am having a bug with it.

In the Heap class:

private serial[] data;
private int size;
private static final int FRONT = 1;
public Heap(){
    serial[] data = new serial[1000]; //serial - object with a String
    this.size = 0;
    data[0] = new serial("");
}

public void insert(serial t){
    size++;
    data[size] = t; **<--- Null Pointer EXCEPTION** 
    int current = size;
    while(data[current].serialNumber() > data[parent(current)].serialNumber()){
        swap(parent(current), current);
        current = parent(current);
    }
}

(and more functions of course for the heap implementation). and the main class:

public class Simulation {

public static void main(String[] args) {
    Heap maxHeap = new Heap();
    maxHeap.insert(new serial("a"));
    maxHeap.insert(new serial("ba"));
    maxHeap.print();

}

}

(I insert Strings and return a sorted array based on numbers) I ran the program, and it returns a Null Pointer Exception (to the insert function, it is written in the code where).

for some reason, it says that: (in the Heap class)

private serial[] data;

was never used.


Solution

  • In the heap constructor I initialized the instance variable again.

    Thanks to Seelenvirtuose