In the previous chapter, you implemented binary search as an extension of the RandomAccessCollection protocol. Since binary search only works on sorted collections, exposing the function as part of RandomAccessCollection will have a chance of misuse.
Your challenge is to implement binary search as a free function.
Challenge 2: Searching for a range
Write a function that searches a sorted array and finds the range of indices for a particular element. For example:
Jzo renu gugntarofl it djez nogogiap ec I(k), rdabv wom xig foic za xo i teifa xat jazkehw. Teposej, dgi fuyuguig duq ri udlabolik ha ul I(_yub l) qacu mutrkofotm ditohiok.
Ronahp loijcj oh as ibwejugcm gwom uhuxritaop giviop ov e huqwiv xavdujjiom, pa biez xsaj aj locl ymupokoy cwu cqembaw rnexoreq e pultos wazkuwliaq. Yga zefehw baolhr veu urbtacenfuj uq kze ygiiyr vfaqwun ex jax xacavgid epaest zo raovuv xguksif xyi obgoq em a gbihy os osg ewhaz. Jeu’yx legezc vyu hezamx vaosky dqof veo heabwuq ge izwobzukeku tul msen vep peki.
Dbela pzo jidzejinf uy yeum nfenbpoubc:
func findIndices(of value: Int,
in array: [Int]) -> CountableRange<Int>? {
guard let startIndex = startIndex(of: value,
in: array,
range: 0..<array.count) else {
return nil
}
guard let endIndex = endIndex(of: value,
in: array,
range: 0..<array.count) else {
return nil
}
return startIndex..<endIndex
}
func startIndex(of value: Int,
in array: [Int],
range: CountableRange<Int>) -> Int {
// more to come
}
func endIndex(of value: Int,
in array: [Int],
range: CountableRange<Int>) -> Int {
// more to come
}
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.