Created
January 21, 2022 03:29
-
-
Save guanguans/1991d3f944c8380d5ede1f0b4abcb139 to your computer and use it in GitHub Desktop.
#PriorityQueue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class PriorityQueue | |
| { | |
| private $queue = []; | |
| public function enqueue($item, $priority) | |
| { | |
| $this->queue[] = [$item, $priority]; | |
| $this->sort(); | |
| } | |
| public function dequeue() | |
| { | |
| return array_shift($this->queue); | |
| } | |
| public function peek() | |
| { | |
| return $this->queue[0] ?? null; | |
| } | |
| public function isEmpty() | |
| { | |
| return empty($this->queue); | |
| } | |
| private function sort() | |
| { | |
| usort($this->queue, function ($a, $b){ | |
| return $a[1] <=> $b[1]; | |
| }); | |
| } | |
| } | |
| $q = new PriorityQueue(); | |
| $q->enqueue('b', 1); | |
| $q->enqueue('d', 3); | |
| $q->enqueue('c', 2); | |
| $q->enqueue('a', 0); | |
| dump($q->dequeue()); | |
| dump($q->dequeue()); | |
| dump($q->dequeue()); | |
| dump($q->dequeue()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment