Skip to content

Instantly share code, notes, and snippets.

@akhilcb
Created November 21, 2017 00:57
Show Gist options
  • Save akhilcb/1531958edf7d819f8aef4c1446af0ddd to your computer and use it in GitHub Desktop.
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.
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
}
}
@akhilcb
Copy link
Author

akhilcb commented Nov 21, 2017

Usage:

Input:

let inputList = ["a", "c", "d", "g", "i", "j"]
print(inputList)

Output:

["a", "c", "d", "g", "i", "j"]

var outputList = inputList
outputList.insertSorted(newItem: "h")
outputList.insertSorted(newItem: "k")
outputList.insertSorted(newItem: "e")
outputList.insertSorted(newItem: "x")
print(outputList)

Output:

["a", "c", "d", "e", "g", "h", "i", "j", "k", "x"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment