Last active
May 26, 2020 05:06
-
-
Save KristopherGBaker/614856d4f08d3909c3e00c12dffcd792 to your computer and use it in GitHub Desktop.
Simple Swift Heap implementation
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
struct Heap<Element: Comparable> { | |
enum HeapType { | |
case min | |
case max | |
func compare(_ lhs: Element, _ rhs: Element) -> Bool { | |
switch self { | |
case .min: | |
return lhs < rhs | |
case .max: | |
return lhs > rhs | |
} | |
} | |
} | |
let type: HeapType | |
var count: Int { | |
return items.count | |
} | |
var isEmpty: Bool { | |
return items.isEmpty | |
} | |
private (set) var items = [Element]() | |
init(type: HeapType) { | |
self.type = type | |
} | |
mutating func delete() -> Element? { | |
guard !isEmpty else { | |
return nil | |
} | |
let val = items[0] | |
items[0] = items[items.count - 1] | |
items.removeLast() | |
if !isEmpty { | |
heapify(at: 0) | |
} | |
return val | |
} | |
mutating func insert(_ value: Element) { | |
items.append(value) | |
reverseHeapify(at: items.count - 1) | |
} | |
private func parent(_ index: Int) -> Int { | |
return (index - 1) / 2 | |
} | |
private func left(_ index: Int) -> Int { | |
return index * 2 + 1 | |
} | |
private func right(_ index: Int) -> Int { | |
return index * 2 + 2 | |
} | |
private mutating func reverseHeapify(at index: Int) { | |
guard index > 0 else { | |
return | |
} | |
let p = parent(index) | |
if type.compare(items[index], items[p]) { | |
items.swapAt(p, index) | |
reverseHeapify(at: p) | |
} | |
} | |
private mutating func heapify(at index: Int) { | |
let l = left(index) | |
let r = right(index) | |
var largest = index | |
if l < items.count, type.compare(items[l], items[index]) { | |
largest = l | |
} | |
if r < items.count, type.compare(items[r], items[largest]) { | |
largest = r | |
} | |
if largest != index { | |
items.swapAt(largest, index) | |
heapify(at: largest) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment