-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpriority-queue.php
35 lines (30 loc) · 1.33 KB
/
priority-queue.php
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
35
<?php
class PriorityQueue {
private $heap; // Array to store heap elements
private $compare; // Comparison function to determine priority
// Constructor to initialize the priority queue with a comparison function
public function __construct(callable $compare) {
$this->heap = []; // Initialize an empty heap array
if (!is_callable($compare)) {
throw new InvalidArgumentException("Compare has to be a function"); // Ensure the comparison function is callable
}
$this->compare = $compare; // Set the comparison function
}
// Method to get the index of the parent node
public function getParentIndex($index) {
return intdiv($index - 1, 2); // Calculate the parent index using integer division
}
// Method to get the index of the left child node
public function getLeftChildIndex($index) {
return 2 * $index + 1; // Calculate the left child index
}
// Method to get the index of the right child node
public function getRightChildIndex($index) {
return 2 * $index + 2; // Calculate the right child index
}
// Method to swap two elements in the heap
public function swap($index1, $index2) {
list($this->heap[$index1], $this->heap[$index2]) = [$this->heap[$index2], $this->heap[$index1]]; // Swap the elements
}
}
?>