I did not understand the error: v variable is been initialized
In the call of the method less(k, v),
inside the insert()
method, because the variable v is initialized in line above... But even so the compiler gave me the error. My code is to insert a key in two priority queue, I added a test that i am doing with integers.
public class MedianPQ <Key extends Comparable<Key>>{
private MaxPq left;
private MinPq right;
public MedianPQ(int N, int M) {
left = new MaxPq(N);
right = new MinPq(M);
}
private boolean less( Key k, Key v) {
return k.compareTo(v) < 0;
}
private boolean great( Key k, Key v) {
return k.compareTo(v) > 0;
}
public void insert(Key k) {
Key v;
if( left.isEmpty() && right.isEmpty()) v = k; // initial
else {
if( less(k, v) && (left.size() < right.size() + 1)) { //error
left.insert(k);
}
else if( great(k, v) && (right.size() < left.size() + 1)) {
right.insert(k);
}
else {
if( left.size() == right.size() + 1) {
right.insert(v);
left.insert(k);
v = (Key)left.max();
}
else {
left.insert(v);
right.insert(k);
v = (Key)right.min();
}
}
}
}
Test:
public static void main(String[] args) {
MedianPQ median = new MedianPQ(100, 100);
Random rnd = new Random();
for( int i = 0; i < 20; i++) {
median.insert(rnd.nextInt(50));
}