Created
November 21, 2017 00:57
-
-
Save akhilcb/1531958edf7d819f8aef4c1446af0ddd to your computer and use it in GitHub Desktop.
Swift Array extension to insert value in a sorted array at correct index. Index is found by using binary search.
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 where Element: Comparable { | |
//insert item to sorted array | |
mutating func insertSorted(newItem item: Element) { | |
let index = insertionIndexOf(elem: item) { $0 < $1 } | |
insert(item, at: index) | |
} | |
} | |
extension Array { | |
//https://stackoverflow.com/a/26679191/8234523 | |
func insertionIndexOf(elem: Element, isOrderedBefore: (Element, Element) -> Bool) -> Int { | |
var lo = 0 | |
var hi = self.count - 1 | |
while lo <= hi { | |
let mid = (lo + hi)/2 | |
if isOrderedBefore(self[mid], elem) { | |
lo = mid + 1 | |
} else if isOrderedBefore(elem, self[mid]) { | |
hi = mid - 1 | |
} else { | |
return mid | |
} | |
} | |
return lo | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Input:
Output:
Output: