mutating func remove() -> Element? {
guard !isEmpty else { return nil } // 1
elements.swapAt(0, elements.count-1) // 2
defer {
siftDown(from: 0) // 4
}
return elements.removeLast() // 3
}
mutating func siftDown(from index: Int) {
var parent = index
while true {
let left = leftChildIndex(ofParentAt: parent)
let right = rightChildIndex(ofParentAt: parent)
var candidate = parent
if left < count && sort(elements[left], elements[candidate]) {
candidate = left
}
if right < count && sort(elements[right], elements[candidate]) {
candidate = right
}
if candidate == parent {
return
}
elements.swapAt(parent, candidate)
parent = candidate
}
}
Can someone explain how the sort function is working here / what it’s doing?