1
+ package com.github.contest.heap.customStructure
2
+
3
+ class MaxHeap <T : Comparable <T >> {
4
+
5
+ private val heap = mutableListOf<T >()
6
+ val size get() = heap.size
7
+
8
+ fun isEmpty () = heap.isEmpty()
9
+
10
+ fun isNotEmpty () = heap.isNotEmpty()
11
+
12
+ fun offer (item : T ) {
13
+ heap.add(item)
14
+ siftUp(heap.size - 1 )
15
+ }
16
+
17
+ fun poll (): T ? {
18
+ if (isEmpty()) throw IndexOutOfBoundsException ()
19
+ heap.swap(0 , heap.size - 1 )
20
+ val element = heap.removeLast()
21
+ siftDown(0 )
22
+ return element
23
+ }
24
+
25
+
26
+ private fun siftUp (index : Int ) {
27
+ var currentIndex = index
28
+ var parentIndex = parentIndex(currentIndex)
29
+ while (currentIndex > 0 && heap[currentIndex] > heap[parentIndex]) {
30
+ heap.swap(currentIndex, parentIndex)
31
+ currentIndex = parentIndex
32
+ parentIndex = parentIndex(currentIndex)
33
+ }
34
+ }
35
+
36
+
37
+ private fun siftDown (index : Int ) {
38
+ var currentIndex = index
39
+ while (hasLeftChild(currentIndex)) {
40
+ var smallestIndex = leftChildIndex(currentIndex)
41
+ if (hasRightChild(currentIndex) && heap[rightChildIndex(currentIndex)] > heap[smallestIndex]) {
42
+ smallestIndex = rightChildIndex(currentIndex)
43
+ }
44
+ if (heap[currentIndex] > heap[smallestIndex]) break
45
+ heap.swap(currentIndex, smallestIndex)
46
+ currentIndex = smallestIndex
47
+ }
48
+ }
49
+
50
+ private fun MutableList<T>.swap (from : Int , to : Int ) {
51
+ val temp = this [from]
52
+ this [from] = this [to]
53
+ this [to] = temp
54
+ }
55
+
56
+ private fun hasLeftChild (index : Int ): Boolean = leftChildIndex(index) < heap.size
57
+
58
+ private fun hasRightChild (index : Int ): Boolean = rightChildIndex(index) < heap.size
59
+
60
+ private fun leftChildIndex (index : Int ) = (index * 2 ) + 1
61
+
62
+ private fun rightChildIndex (index : Int ) = (index * 2 ) + 2
63
+
64
+ private fun parentIndex (index : Int ) = (index - 1 ) / 2
65
+
66
+ }
0 commit comments