Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Last active December 1, 2019 05:03
Show Gist options
  • Save jakehawken/c8b00e2a366f8abf2170 to your computer and use it in GitHub Desktop.
Save jakehawken/c8b00e2a366f8abf2170 to your computer and use it in GitHub Desktop.
class Heap {
private var elements : [Int]
init() {
elements = [Int]()
}
func insert(number: Int) -> Void {
if elements.count == 0 {
elements.append(0)
elements.append(number)
return
}
elements.append(number)
bubbleUpIfNeededFromIndex(elements.count - 1)
}
func minimum() -> Int {
return elements.first! + 1
}
private func bubbleUpIfNeededFromIndex(index: Int) -> Void {
if index <= 1 {return}
let parentIndex = Int(index/2)
if elements[index] < elements[parentIndex] {
swapElements(atIndex: index, andIndex: parentIndex)
bubbleUpIfNeededFromIndex(parentIndex)
}
}
private func swapElements(atIndex firstIndex: Int, andIndex secondIndex: Int) -> Void {
let firstValue = elements[firstIndex]
let secondValue = elements[secondIndex]
elements[secondIndex] = firstValue
elements[firstIndex] = secondValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment