Skip to content

Instantly share code, notes, and snippets.

@guanguans
Created January 21, 2022 03:29
Show Gist options
  • Save guanguans/1991d3f944c8380d5ede1f0b4abcb139 to your computer and use it in GitHub Desktop.
Save guanguans/1991d3f944c8380d5ede1f0b4abcb139 to your computer and use it in GitHub Desktop.
#PriorityQueue
<?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