Skip to content

Commit 4615c45

Browse files
add impl max heap
1 parent 07447ef commit 4615c45

File tree

2 files changed

+74
-2
lines changed

2 files changed

+74
-2
lines changed

contest/src/main/java/com/github/contest/Execute.kt

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package com.github.contest
22

3-
import com.github.contest.backtracking.getHappyStringProdVariant
3+
import com.github.contest.heap.customStructure.MaxHeap
44

55

66
/**
@@ -9,7 +9,13 @@ import com.github.contest.backtracking.getHappyStringProdVariant
99

1010
fun main() {
1111

12-
getHappyStringProdVariant(3, 9).also { println(it) }
12+
val maxheap = MaxHeap<Int>()
13+
14+
for (i in 1..39) maxheap.offer(i)
15+
16+
while (maxheap.isNotEmpty()) {
17+
println(maxheap.poll())
18+
}
1319

1420

1521
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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

Comments
 (0)