Last active
December 1, 2019 05:03
-
-
Save jakehawken/c8b00e2a366f8abf2170 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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