Skip to content

Instantly share code, notes, and snippets.

@kalub92
Created March 5, 2018 22:07
Show Gist options
  • Save kalub92/e2272901b55965675c3d8544d476dff8 to your computer and use it in GitHub Desktop.
Save kalub92/e2272901b55965675c3d8544d476dff8 to your computer and use it in GitHub Desktop.
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
}
private func getParentIndex(_ childIndex: Int) -> Int {
return (childIndex - 1) / 2
}
// Boolean Check
private func hasLeftChild(_ index: Int) -> Bool {
return getLeftChildIndex(index) < items.count
}
private func hasRightChild(_ index: Int) -> Bool {
return getRightChildIndex(index) < items.count
}
private func hasParent(_ index: Int) -> Bool {
return getParentIndex(index) >= 0
}
// Return Item From Heap
private func leftChild(_ index: Int) -> Int {
return items[getLeftChildIndex(index)]
}
private func rightChild(_ index: Int) -> Int {
return items[getRightChildIndex(index)]
}
private func parent(_ index: Int) -> Int {
return items[getParentIndex(index)]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment