Last active
March 17, 2020 09:15
-
-
Save madcato/53aca6d72fe567b6efbe10d2a7782c54 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
extension Array { | |
/** | |
Insert an element at a position ordered. | |
Precondition: the array must be already sorted. | |
- parameter element: element to insert | |
- parameter orderedBy: This block must return $0 < $1 | |
*/ | |
mutating func insert(ordered element: Element, orderedBy: (_ A: Element, _ B: Element) -> Bool) { | |
var low = 0 | |
var high = self.count - 1 | |
while low <= high { | |
let mid = (low + high) / 2 | |
if orderedBy(self[mid], element) { | |
low = mid + 1 | |
} else if orderedBy(element, self[mid]) { | |
high = mid - 1 | |
} else { | |
self.insert(element, at: mid) | |
return | |
} | |
} | |
self.insert(element, at: low) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment