0

I'm trying to extend PHP's SplMinHeap so I can limit the amount of items my heap can hold. The problem is, when I try to access the top element, which should be the min, it gives me the max value. The code I have so far is pretty simple:

class MyHeap extends SplMinHeap {
    public static $limit = 10;

    public function compare($value1, $value2) {
         return ($value1 - $value2);
    }

    public function myInsert($value) {
        if ( $this->count() < self::$limit ) {
            $this->insert($value);
        } else {
            var_dump($this->top());
        }
    }
};

When I insert the numbers 1 to 15 I would expect it to print 1 5 times, instead it prints 10. I also tried extending the insert method, using the same code as myInsert but replacing $this->insert with parent::insert. I just didn't know whether that would use my extended compare or the default one, that's why I switched it.

Strangely enough, if use a normal SplMinHeap and insert the same numbers I will get 1 when calling top().

Can anyone help me figure out what I'm doing wrong?

Felipe Ruiz
  • 181
  • 1
  • 6
  • 1
    It seems that defining compare function defines the heap type. If you will create your own compare function - you will have your own heap type) Good luck. – u_mulder May 26 '13 at 16:51
  • @u_mulder which is probably a good reason for not doing so :) – vascowhite May 26 '13 at 16:59

2 Answers2

2

The problem is the compare method. Just change compare

public function compare($value1, $value2) {
     return ($value2 - $value1);
}

and you will get your SplMinHeap. Also I think you should extend SplHeap class, not SplMinHeap.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

I'm not sure what your compare method is meant to achieve, as it is doing exactly the same as the default compare method, but removing it resolves the problem. You have declared the compare method as public, which generate a warning as the method in the base class is protected.

Also you can override the insert method directly and everything will work fine:-

class MyHeap extends SplMinHeap {
    public static $limit = 10;

    public function insert($value) {
        if ($this->count() < self::$limit) {
            parent::insert($value);
        } else {
            var_dump($this->top());
        }
    }
};
vascowhite
  • 18,120
  • 9
  • 61
  • 77