-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.kt
More file actions
78 lines (64 loc) · 2.08 KB
/
Copy pathMaxHeap.kt
File metadata and controls
78 lines (64 loc) · 2.08 KB
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
package structures
/**
* data structure: max-heap
*
* | operation | time
* ----------------------------------------------
* | getting the maximum element | O(1)
* | --------------------------------------------
* | inserting a new element | O(logn)
* | --------------------------------------------
* | deleting an element | O(logn)
*
* description: max-heap is a binary tree in which each parent is greater than its children
*
*/
class MaxHeap(private val maxSize: Int) {
private val heap = Array(maxSize + 1) { 0 }.apply {
this[0] = Int.MAX_VALUE
}
private val root = 1
private var size = 0
private fun parent(pos: Int) = pos / 2
private fun leftChild(pos: Int) = 2 * pos
private fun rightChild(pos: Int) = 2 * pos + 1
private fun swap(old: Int, new: Int) {
heap[old] = heap[new].apply { heap[new] = heap[old] }
}
fun isEmpty() = size == 0
fun add(element: Int) {
fun heapifyUp(pos: Int) {
var current = pos
val temp = heap[pos]
while (current > 0 && temp > heap[parent(current)]) {
heap[current] = heap[parent(current)]
current = parent(current)
}
heap[current] = temp
}
heap[++size] = element
heapifyUp(size)
}
fun peekMax() = heap[root]
fun popMax(): Int {
fun downHeapify(pos: Int) {
if (pos >= size / 2 && pos <= size) return
if (pos == maxSize - 1) return
if (heap[pos] < heap[leftChild(pos)] ||
heap[pos] < heap[rightChild(pos)]
) {
if (heap[leftChild(pos)] > heap[rightChild(pos)]) {
swap(pos, leftChild(pos))
downHeapify(leftChild(pos))
} else {
swap(pos, rightChild(pos))
downHeapify(rightChild(pos))
}
}
}
val max = heap[root]
heap[root] = heap[size--]
downHeapify(root)
return max
}
}