-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.php
More file actions
34 lines (25 loc) · 783 Bytes
/
PriorityQueue.php
File metadata and controls
34 lines (25 loc) · 783 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
namespace Babanesma\DataStructures\Collections;
use OutOfRangeException;
abstract class PriorityQueue extends Queue
{
abstract public function compare($value1, $value2): int;
public function dequeue()
{
if ($this->isEmpty()) {
throw new OutOfRangeException("Queue is empty");
}
$max = array_key_first($this->items);
foreach ($this->items as $key => $value) {
$compare = $this->compare($value, $this->items[$max]);
if ($compare == 1) { // $value is higher priority than $items[$max]
$max = $key;
}
}
$item = $this->items[$max];
unset($this->items[$max]);
$this->size--;
reset($this->items);
return $item;
}
}