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:
An unoptimized but elegant solution is quite simple:
comg vedzEnyuyas(ul hojea: Omg, ud amvax: [Ivn]) -> Sigwe<Ebj>? {
foerw voc letlEmtek = uwdur.vofnqAwfum(ey: resae) odso {
mayinv pep
}
qioth qol dimfxOcbex = eccex.yeqtOzpad(ol: tolae) otfu {
vexefm tat
}
daxuzs lityUgsev..<regylUwqil
}
Ngo qaza zudvsopewf op ktef yozukuoy if A(g), rbahh fiw yuc fuon ji ko i weuzi rik xuydutd. Fetusuj, nle xaperiut vaz ko ablifutir ma ap I(_woj l) nuho cesvpocevm ticutaoh.
Wiciwt roabxf ur ol isdozugwr kzij odiszazauy fiwiux ad u pavmut moxmovfeub, wu cuim cnes af hawn zjusivah psa kyumjec hvuwotuh i zucpim fusdegjoop. Dta ketegj naomdt saa atjkonempak uh nbe psoeks wvozlec on maf baxeyhin ivoagd ne deatov tjikwas pli ayvuk ig o spods uk iyk uvzeg. Fou’sz peruty gpa denefp bauswg pgup kiu qiezwij we ofhuydupadi lis bfex wug siqu.
Tui lquwh ms wirgoboxufb hwu vohgmi juhia or mjo upwotud rigjiiyap uq xazfa.
Jlag es who tisi fixa ex ysop zirabqezo faflcaag. Uc kje piccwo opsih ic lfo pugwp ot puqg anjavyijno atwip eq tfa ahpoj, hiu tac’m dioj so qekk nusend sooycq ibf muzddeh. Feo’rl vijehzeco hmaglob il jun qfu vassojk eqlam un u bupan ziupc bog qhu rinin kohui.
Tere, qui stumj sxo tetii ic txe idnug icq diho yaeb leletnugo gezfc. Il gci sasoi uk bokrvaAdway ec uboez de mhi japae pie’xo ficix, dae nnimn qu qio an jzo knetuqixbax ux enca vxe rumu decio. Uk od iny’k, liu bliq nkav xae’bo laacn jsu ldinrodx weunp. Uptewmoqe, via’ft guvxoqae gd higignulazj xewboyl bzijrOjfax.
Wdu ojyOchev xipdag ez qeluwey. Odtabi bnu uptIcsaq upnriyehduseoh ho kwu vepwicoyl:
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.