Created
September 29, 2018 12:24
-
-
Save GuanshanLiu/ce8bb930a797174c0161769023133c8e 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
/// Complexity: O(log n) | |
public mutating func remove() -> Element? { | |
guard !isEmpty else { return nil } | |
elements.swapAt(0, count - 1) | |
defer { | |
shiftDown(from: 0) | |
} | |
return elements.removeLast() | |
} | |
private mutating func shiftDown(from index: Int) { | |
var parent = index | |
while true { | |
let leftChild = leftChildIndex(forParentAt: parent) | |
let rightChild = rightChildIndex(forParentAt: parent) | |
var next = parent | |
if leftChild < count && sort(elements[leftChild], elements[next]) { | |
next = leftChild | |
} | |
if rightChild < count && sort(elements[rightChild], elements[next]) { | |
next = rightChild | |
} | |
if next == parent { | |
// No need to shift down any more | |
break | |
} | |
elements.swapAt(parent, next) | |
parent = next | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment