Skip to content

Core\Heap::push

$heap->push(T $value): void$heap->push(
    T $value,
): void

Adds a value to a heap. A heap keeps its values in order, so the smallest value is always ready to take out.

A heap is also called a priority queue. push puts the new value in its right place, and this stays fast even when the heap has many values. If you add the same value twice, the heap keeps both. The heap decides what "smallest" means in this order: the comparator function you gave to new Core\Heap, then the compareTo method of objects that implement Comparable, then the normal order of numbers and strings.

In plain words: a heap is like a pile of tasks where the most urgent task is always on top. You can add a task at any time, and it goes to its right place in the pile.

Good to know: if two values cannot be compared, push throws a RuntimeError.

Parameters

  • $valueTThe element to add.

Return value

Returns void. Nothing. If the comparator throws an error, push throws the same error.

Errors

  • RuntimeErrorThe heap cannot compare $value with another element. There is no comparator or compareTo, and the two values have no natural order. Two numbers, two strings, two bools or two nulls have one. It also throws when the comparator returns NaN.

Examples

Smallest comes out first

<?nvs
// Shows that `push` keeps a heap in order. The numbers go in mixed up and come out smallest first.
var $heap = new Core\Heap<int>();
$heap->push(5);
$heap->push(2);
$heap->push(8);
$heap->push(1);
// This prints 1, 2, 5 and 8.
while (!$heap->isEmpty()) {
echo $heap->pop(), "\n";
}
Output
1
2
5
8

The same value twice

<?nvs
// Shows that a heap keeps every value you add, even the same value twice.
var $heap = new Core\Heap<string>();
$heap->push('pear');
$heap->push('apple');
$heap->push('apple');
// This prints 3.
echo $heap->count(), "\n";
// Strings come out in alphabetical order. This prints apple, apple and pear.
while (!$heap->isEmpty()) {
echo $heap->pop(), "\n";
}
Output
3
apple
apple
pear

A queue of support tickets

<?nvs
// Shows a queue of support tickets. The most urgent ticket is handled first.
class Ticket implements Comparable
{
public string $title;
public int $priority;
public function constructor(string $title, int $priority)
{
$this->title = $title;
$this->priority = $priority;
}
// A smaller number is more urgent, so priority 1 comes out first.
public function compareTo(Ticket $other): int
{
return $this->priority - $other->priority;
}
}
var $queue = new Core\Heap<Ticket>();
$queue->push(new Ticket('Change the invoice address', 3));
$queue->push(new Ticket('The shop is down', 1));
$queue->push(new Ticket('Reset my password', 2));
// This prints the tickets in the order 1, 2, 3.
while (!$queue->isEmpty()) {
var $ticket = $queue->pop();
echo $ticket->priority, ': ', $ticket->title, "\n";
}
Output
1: The shop is down
2: Reset my password
3: Change the invoice address