Search code examples
javatype-conversionkeydoublepriority-queue

Convert Double to Key (Priority queue)


I've been on an extensive search through the interwebs looking for some type of answer to my problem, but I've had no luck finding anything that can help me. Basically what I wonder about is if it is possible to convert a double into a Key that then is inserted into a Priority Queue.

This is the method I'm struggling with is from a file name MedianPQ.java. It's this one:

public void insert(Double a){
        if (size == 0 || a.compareTo(findMedian()) == 1) minPQ.insert(a);
        else maxPQ.insert(a);
        rearrange();
        size++;
    }

The insert method in the MinPQ.java file looks like this:

public void insert(Key x) {
        // double size of array if necessary
        if (n == pq.length - 1) resize(2 * pq.length);

        // add x, and percolate it up to maintain heap invariant
        pq[++n] = x;
        swim(n);
        assert isMinHeap();
    }

And here is the insert method from MaxPQ.java

public void insert(Key x) {

        // double size of array if necessary
        if (n == pq.length - 1) resize(2 * pq.length);

        // add x, and percolate it up to maintain heap invariant
        pq[++n] = x;
        swim(n);
        assert isMaxHeap();
    }

They are identical. Now the problem arises as public void insert(Double a) from MedianPQ.java must not be changed. I have to take in a double and then insert that double into the PQ. But the methods from MinPQ.java and MaxPQ.java only inserts a key. Is it possible to just convert the double to a key inside the insert(Double a) method???


Solution

  • You should use Double as generic for MaxPQ and MinPQ. To do this try following:

    public static void main(String[] args) {
        MedianPQ<Double> median = new MedianPQ<Double>(10, 20);
        median.insert(1.1D);
        median.insert(2.2D);
    }
    

    Or

    private MaxPq<Double> left;
    private MinPq<Double> right;
    

    Hope it helps.