You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* @see https://github.com/jonasmalacofilho/dheap (Haxe - Jonas Malaco Filho)
8
+
*
9
+
* @author azrafe7
10
+
*/
11
+
12
+
packagehxGeomAlgo;
13
+
14
+
importhxGeomAlgo.Debug;
15
+
16
+
17
+
/** Heap elements must implement this interface. */
18
+
interfaceHeapable<T> {
19
+
20
+
/** Used internally by Heap. Do not modify. */
21
+
varposition:Int;
22
+
23
+
/**
24
+
* Returns the result of comparing `this` to `other`, where the result is expected to be:
25
+
* less than zero if `this` < `other`
26
+
* equal to zero if `this` == `other`
27
+
* greater than zero if `this` > `other`
28
+
*/
29
+
functioncompare(other:T):Int;
30
+
}
31
+
32
+
33
+
/**
34
+
* Heap implementation (over Array).
35
+
*
36
+
* Note: depending on the compare function (i.e. if it's ascending or descending),
37
+
* it will act as a MinHeap or MaxHeap (meaning that `pop()` will return the smallest
38
+
* or the largest element respectively).
39
+
*
40
+
* @author azrafe7
41
+
*/
42
+
classHeap<T:Heapable<T>>
43
+
{
44
+
privatevardata:Array<T>;
45
+
46
+
publicfunctionnew():Void
47
+
{
48
+
data=newArray<T>();
49
+
}
50
+
51
+
/** Number of elements in the Heap. */
52
+
publicvarlength(default, null):Int=0;
53
+
54
+
/** Inserts `obj` into the Heap. */
55
+
publicfunctionpush(obj:T):Void
56
+
{
57
+
vari=length;
58
+
set(obj, i);
59
+
length++;
60
+
if (length>1) bubbleUp(i);
61
+
}
62
+
63
+
/** Returns the root element (i.e. the smallest or largest, depending on compare()) and removes it from the Heap. Or null if the Heap is empty. */
64
+
publicfunctionpop():T
65
+
{
66
+
if (length==0) returnnull;
67
+
68
+
varres=data[0];
69
+
varlen=length;
70
+
varlastObj=data[len-1];
71
+
data[len-1] =null;
72
+
length--;
73
+
if (len>1) {
74
+
set(lastObj, 0);
75
+
bubbleDown(0);
76
+
}
77
+
78
+
returnres;
79
+
}
80
+
81
+
/** Returns the root element (i.e. the smallest or largest, depending on compare()) without removing it from the Heap. Or null if the Heap is empty. */
82
+
publicfunctiontop():T
83
+
{
84
+
returnlength>0?data[0] :null;
85
+
}
86
+
87
+
/** Removes `obj` from the Heap. Checks for correctness are only done in debug. */
88
+
publicfunctionremove(obj:T):Int
89
+
{
90
+
varpos=obj.position;
91
+
Debug.assert((pos>=0&&pos<length), "Object not found.");
92
+
Debug.assert(data[pos] ==obj, '`obj` and retrieved object at $pos don\'t match.');
0 commit comments