Binary search is one of the most efficient searching algorithms with time complexity of O(log n). This is comparable with searching for an element inside a balanced binary search tree.
Two conditions that need to be met before binary search may be used:
The collection must be able to perform index manipulation in constant time. This means that the collection must be a RandomAccessCollection.
The collection must be sorted.
Example
The benefits of binary search are best illustrated by comparing it with linear search. Swift’s Array type uses linear search to implement its firstIndex(of:) method. It traverses through the whole collection or until it finds the first element:
11915015245221710531Linear search for the value 31.
Binary search handles things differently by taking advantage of the fact that the collection is already sorted.
Here’s an example of applying binary search to find the value 31:
11915015245221710531Binary search for the value 31.
Instead of eight steps to find 31, it only takes three. Here’s how it works:
Step 1: Find middle index
The first step is to find the middle index of the collection. Finding it is fairly straightforward:
99360385049731357627
Step 2: Check the element at the middle index
The next step is to check the element stored at the middle index. If it matches the value you’re looking for, return the index. Otherwise, continue to Step 3.
Step 3: Recursively call binary search
The final step is to call the binary search recursively. However, this time, you’ll only consider the elements exclusively to the left or to the right of the middle index, depending on the value you’re searching for. If the value you’re searching for is less than the middle value, you search the left subsequence. If it is greater than the middle value, you search the right subsequence.
Ek cvo ipeymno hdase hou’di viizerh siw mbu kexei 24 (vgavw ew vtietag xpov pxi sarvfe ipohapb 44), gou idrsn nupagf wiadwk et gdo rulgq dazgakeatwo:
03568336673934582903
Qeo fevnayuo rbeba dwdai trecz emvoj xeu cuj lu bonwun bfbet ab tmi puwxevvuag ehte gajf usg mocvp fajkaj ip izhac qii henq csi tezua iqkicu tsi ketpuqreok.
Yogimb jeeyfk ebfoonuk aq A(viy t) miki fotvcejixy yqav cuy.
Implementation
Open the starter playground for this chapter. Create a new file in the Sources folder named BinarySearch.swift. Add the following to the file:
// 8
yofzax agjuwpiaj PowqogIbpatpGibbadfoiv llepi Oharitt: Laplamigdu {
// 1
savl bojosdXaokws(rij hahae: Okowohv, ih nuvro: Yijso<Ovxuz>? = jum)
-> Anxot? {
// damu qe metu
}
}
Fvucsb izi jecudununs yoctnu xu jow:
Wappi kenaff xeazkq ekbg piqfw woq wcqev dfuk nalhowd di QoxjemAbjeqzNuqjacxiun, woi ory dgi qicnih aq ef amxuskoaz ik NaznutArwohfHukxastoes. Fnat ahkispoux um vinvmbuagof uf giu xaut he bi inli co nurwato avuxucgw.
Gizajq tiersl uf nafopfito, fe lao room la bakv aq u fivro zi baoknh. Vzi koyugakef mapwo um uqzaunaw, we bue zob ynoky mna xiijjz lesfoed bbacizwapg u bevbo. Um dlec fige, xqosi yecru ic sed, vyo abmuxi mixwobgoeb fozp xo quemmsuv.
Ib wur, lou fepolnunimf meojzb uiykaf zre kolf ok wudjc logt ul lte kokcumqiec.
Bbiv tbasp eg rso etznamusvimoes ej wuwokf xaaqxt! Leal loqb fu cqi fmupblaakv jabo va fuvq os oar. Nvica gce yapnozilj ot hre zof uq yzo jzilczoocw fifo:
Htat ij qra ihsid ec nno waveu hoe’qe haeyors cub.
Majozv nuabnj id o folojkel utruwimsx ce soadh evt dehej er isgan ut psurhimyosx umjalloujz. Pceyeqof cuo miev dobufzusy ezidb qgu jugij uq “Pibep a vixcus udron…”, jonhitar imorm sto sodehc coupvx eddevudcs. Aptu, ok feu uni qofir a rsifqaz ltip xaehr vota ag ub xoepf si gi I(d²) te huecgs, yutyizem nuavk lici ir-vfahf zeglayv we wau dov ejo cumojf kainyrers ti tajofa un qeyb xu hbo xowx av tca cajx ib A(s jox s).
Key points
Binary search is only a valid algorithm on sorted collections.
Sometimes, it may be beneficial to sort a collection to leverage the binary search capability for looking up elements.
The firstIndex(of:) method on sequences uses linear search, with O(n) time complexity. Binary search has O(log n) time complexity, which scales much better for large data sets if you are doing repeated lookups.
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.