Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Last active July 24, 2025 16:18
Show Gist options
  • Save DanielCardonaRojas/922b78c266187aeb1c73a395af7abd29 to your computer and use it in GitHub Desktop.
Save DanielCardonaRojas/922b78c266187aeb1c73a395af7abd29 to your computer and use it in GitHub Desktop.
MaxHeap implementation
class MaxHeap {
private var array: [Int] = []
private var heapSize = 0
private func parentIndex(_ index: Int) -> Int {
(index - 1) / 2
}
private func leftChildIndex(_ index: Int) -> Int {
2 * index + 1
}
private func rightChildIndex(_ index: Int) -> Int {
2 * index + 2
}
private func hasLeftChild(_ index: Int) -> Bool {
leftChildIndex(index) < heapSize
}
private func hasRightChild(_ index: Int) -> Bool {
rightChildIndex(index) < heapSize
}
func peek() -> Int {
array[0]
}
func pop() -> Int {
swap(0, array.count - 1)
let result = array.removeLast()
heapSize = array.count
heapifyDown(0)
return result
}
func insert(_ value: Int) {
array.append(value)
heapSize = array.count
heapifyUp(heapSize - 1)
}
func heapifyDown(_ index: Int) {
var largest = index
let left = leftChildIndex(index)
let right = rightChildIndex(index)
if left < heapSize && array[left] > array[largest] {
largest = left
}
if right < heapSize && array[right] > array[largest] {
largest = right
}
if largest != index {
swap(index, largest)
heapifyDown(largest)
}
}
func heapifyUp(_ index: Int) {
guard index != 0 else {
return
}
let value = array[index]
let parentIndex = parentIndex(index)
let parent = array[parentIndex]
if value > parent {
swap(index, parentIndex)
}
heapifyUp(parentIndex)
}
func swap(_ firstIndex: Int, _ secondIndex: Int) {
let tmp = array[firstIndex]
array[firstIndex] = array[secondIndex]
array[secondIndex] = tmp
}
func dump() {
print(array)
}
func sort() {
while heapSize > 0 {
swap(0, heapSize - 1)
heapSize -= 1
heapifyDown(0)
}
heapSize = array.count
}
func sorted() -> [Int] {
sort()
return array
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment