-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminHeap.php
108 lines (74 loc) · 1.81 KB
/
minHeap.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
class MinHeap {
public $heap = array();
public function Insert($data) {
$count = count($this->heap);
if(!$count) {
$this->heap[1] = $data;
} else {
$this->heap[$count+1] = $data;
$this->bubbleUp();
}
}
private function bubbleUp() {
$position = count($this->heap);
$newpos = round($position/2);
while($position>1 ) {
if($this->heap[floor($position/2)]>$this->heap[$position]) {
$this->swap(floor($position/2),$position);
}
$position = floor($position/2);
}
}
public function ExtractMin() {
$min = $this->heap[1];
$count = count($this->heap);
if($count>1) {
$this->swap(1,$count);
unset($this->heap[$count]);
$count--;
$this->sinkDown(1);
} else {
unset($this->heap[$count]);
}
return $min;
}
private function swap($pos1,$pos2) {
if(isset($this->heap[$pos1]) && isset($this->heap[$pos2])) {
$temp = $this->heap[$pos1];
$this->heap[$pos1] = $this->heap[$pos2];
$this->heap[$pos2] = $temp;
} else {
throw new Exception ("Invalid index");
}
}
private function sinkDown($position) {
$count = count($this->heap);
$smallest = $position;
if($count>1) {
if(2*$position<=$count && $this->heap[$smallest]>$this->heap[2*$position] ) {
$smallest = 2*$position;
}
if(2*$position+1<=$count && $this->heap[$smallest]>$this->heap[2*$position+1] ) {
$smallest = 2*$position+1;
}
if($smallest!=$position) {
$this->swap($smallest,$position);
return $this->sinkDown($smallest);
}
}
return;
}
}
$minHeap = new MinHeap;
$array = [3,2,1,7,8,4,10,16,12];
foreach($array as $number) {
$minHeap->Insert($number);
}
print_r($minHeap->heap);
foreach($minHeap->heap as $number) {
$result[] = $minHeap->ExtractMin();
//print_r($minHeap->heap);
}
print_r($result);
?>