Skip to content

Instantly share code, notes, and snippets.

View kalub92's full-sized avatar

Caleb Stultz kalub92

View GitHub Profile
struct MinHeap {
var items: [Int] = []
//Get Index
private func getLeftChildIndex(_ parentIndex: Int) -> Int {
return 2 * parentIndex + 1
}
private func getRightChildIndex(_ parentIndex: Int) -> Int {
return 2 * parentIndex + 2
}
struct MinHeap {
var items: [Int] = []
}
public func peek() -> Int {
if items.count != 0 {
return items[0]
} else {
fatalError()
}
}
mutating public func poll() -> Int {
if items.count != 0 {
let item = items[0]
items[0] = items[items.count - 1]
heapifyDown()
items.removeLast()
return item
} else {
fatalError()
}
mutating public func add(_ item: Int) {
items.append(item)
heapifyUp()
}
mutating private func swap(indexOne: Int, indexTwo: Int) {
let placeholder = items[indexOne]
items[indexOne] = items[indexTwo]
items[indexTwo] = placeholder
}
mutating private func heapifyUp() {
var index = items.count - 1
while hasParent(index) && parent(index) > items[index] {
swap(indexOne: getParentIndex(index), indexTwo: index)
index = getParentIndex(index)
}
}
mutating private func heapifyDown() {
var index = 0
while hasLeftChild(index) {
var smallerChildIndex = getLeftChildIndex(index)
if hasRightChild(index) && rightChild(index) < leftChild(index) {
smallerChildIndex = getRightChildIndex(index)
}
if items[index] < items[smallerChildIndex] {
break
var myHeap = MinHeap()
myHeap.add(2)
myHeap.add(10)
myHeap.add(8)
myHeap.add(9)
myHeap.add(7)
myHeap.add(3)
myHeap.add(4)
myHeap.peek() // Prints 2 to the console on the right in Swift Playgrounds
myHeap.poll()
dump(myHeap.items)