Skip to content

Instantly share code, notes, and snippets.

@madcato
Last active March 17, 2020 09:15
Show Gist options
  • Save madcato/53aca6d72fe567b6efbe10d2a7782c54 to your computer and use it in GitHub Desktop.
Save madcato/53aca6d72fe567b6efbe10d2a7782c54 to your computer and use it in GitHub Desktop.
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