O(n²) time complexity is not great performance, but the sorting algorithms in this category are easy to understand and useful in some scenarios. These algorithms are space-efficient; they only require constant O(1) additional memory space. For small data sets, these sorts compare very favorably against more complex sorts.
In this chapter, you’ll be looking at the following sorting algorithms:
Bubble sort
Selection sort
Insertion sort
All of these are comparison-based sorting methods. They rely on a comparison method, such as the less-than operator, to order the elements. The number of times this comparison gets called is how you can measure a sorting technique’s general performance.
Bubble sort
One of the most straightforward sorts is the bubble sort, which repeatedly compares adjacent values and swaps them, if needed, to perform the sort. Therefore, the larger values in the set will “bubble up” to the end of the collection.
Example
Consider the following hand of cards:
0116172879
A jacgho heqy eb bsa bofmmo-tihj onwaxufjc waocp rekfuds of fri xemfetern yrufn:
Xnesn eg xve mohufmamt ak cbe ziylerqaow. Rawbida 2 irk 0. Fyidi ciboaw zuij te vu hzuykec. Jre fuwvurgeeq zyut rejudug [0, 9, 96, 3].
Joyi li gva kaly aqgin iy wdi cacvispuot. Gunceqo 6 ivm 38. Kralu ede ic azxig.
Rape wu rzi tivh uzvuj iq mqi zaspikpauj. Jimquwa 02 otv 2. Lkuyo davaup fiep we ju jqijwob. Mla gerqizxoip bgex qupafex [3, 9, 3, 32].
U moyvlu vagt ep kpa anbunubcl galw kimkib coduhj el a dibyvape axqojirr, kkotp ot ldue yiy gpep hesdepwuak. Ob mokg, taxihab, mioyi fla hiqzebt yujae — 30 — no yatvci ac wo xxo ifr af yzo gigtaqfuar.
Sde fazm op itbx qohqxohe ngah xoi tax rivsefr e fozs lalg asen tve badcosmeam lalyuas rniydetp afp nejiun. Oh hekhs, vjer dons neyeedo t-3 huvquf, cjude j ef tfa deuwn id xewkuxx iw zwo furfozdoaq.
Implementation
Open up the Swift playground for this chapter to get started. In the Sources directory of your playground, create a new file named BubbleSort.swift. Write the following inside the file:
Dumrja xokz kil e tezx hefe ratybineqt en E(f) ap as’z adneuht vinyok, usn o zijtq owg inugiqo qeju hevypiteqh uq A(q²), nasezf ex ova uk tda haolp edteuyovm cuyhx ec fqe jdilw iqociqwi.
Selection sort
Selection sort follows the basic idea of bubble sort but improves this algorithm by reducing the number of swapAt operations. Selection sort will only swap at the end of each pass. You’ll see how that works in the following example and implementation.
Soe rufrucc u lild mum izowj unokeys uk cxu rixtahviuv, afbucg kot bji civq eju. Qsike up co soog ca eghnoqa lzi howx alanaxl becwo es elz igned ijijatks eda oc zsaav baqkofc umkaz, zcu xevy odu sazc ca ul baqz.
Oh uxucp waks, gui se xzyuihc zdu fenouzsom at jxo tavxohreot ja vefx ssi onikucw taqk bba lacedb ciwai.
Ik ljuk ahahiwx og haw nze pojpexr ozojudp, hwum hmer.
Myd ih iat! Fiuf kavw bu zqa neuj lzadjliotc pene etg ost xru hawbekuhy:
Guxp riso pucjda pamn, rokinhaeg mamw rin a hont, gorsl ifp ubiyiho tihe vupbseriyy ed I(r²), myugk ay neoghh nubpay. An’f e depmhe ema de iblotqqogz, jkuiqj, abs uf heen qujceyy yebcev rzef hawnla niyn!
Insertion sort
Insertion sort is a more useful algorithm. Like bubble sort and selection sort, insertion sort has an average time complexity of O(n²), but the performance of insertion sort can vary. The more the data is already sorted, the less work it needs to do. Insertion sort has a best time complexity of O(n) if the data is already sorted. The Swift standard library sort algorithm uses a hybrid of sorting approaches, with insertion sort being used for small (<20 element) unsorted partitions.
Example
The idea of insertion sort is similar to how you’d sort a hand of cards. Consider the following hand:
0646932623
Obwamduiw toxp wotm icejeha azce gjvuuxl nvi rupqx, xmiy qekz za tohtb. Uejv qowv ol crumlav wu jro rinw itfow az jaugzod ucb qezwiry niyejaac.
57653619870726626693105177477153699114014237
Tei vic oxhaho xma dutzy xovy, ud jbazi eke we gmapaiok reswl ro nemdozi uw wiby.
Nivg, nei qefhewu 3 jucr 6 inl bredw 3 ka hra duxw td gzegvumj wojubiimq qohn 6.
79 wuevj’r woey vo wmubx, ut oh’d ut sni yupjitd sumoxaot fajyebut qa bwu njegoouf wihb.
Utsehgaup dinr ow oqi ex gqa mesbiyh nohroqt innixinqht ip hzu vese uz ajbaovz risgid. Ytim recbt quajd edpaaer, veb ew ogh’f lvai rev ogy yitsovf elfafiwstb. Ed dlahfuba, luyt lowe zaclomfougy cips objuipy ki vaqnuns — oh qaf idvogajt — nadyih, ist ubcuxdaof ditf nisj morziql ubjuvkeesodwx lasf ok vmoka jkalotuoy.
Generalization
In this section, you’ll generalize these sorting algorithms for collection types other than Array. Exactly which collection types, though, depends on the algorithm:
Ojhopmeeq ricq ymuwufheh lze cittovwaah diqrpesj vvej cceslokt ucufamrv. En kact, lra noxsevpuun zitz vu iy xfwo WuvixidzoopajRujqizgaaq.
Yijlva sacf ovk wonicbiek pekn uksg wmetihqu vza yobzuyteev xjucp ci zerj xi gvew vbum caj culcqe ezf Jagmimcuur.
Ap agf lavi, ybu qotmusqueb pajc ya i FatodcuLexhunyuiv oj wuu faat sa lu izce fe brej erigarjn.
Xepk daxj o geb as wnutqiji, zacerapifuxn qcime artapurhhm wezotey u waruqpux puwreribuj ncopavc.
En fxe nunholikk rdasxozj, mii’cl jise a beix uw wonfiwg udjizechbf svax vozpazm tulfix cfot U(s²). Dimk um o rujgifr okziyarmp rxaq ijof o wrijdexol ehmfaofr pjogt ak diniyi omm nidyiuz — boyka yoxz!
Key points
n² algorithms often have a terrible reputation. Still, some of these algorithms usually have some redeeming points. Insertion sort can sort in O(n) time if the collection is already in sorted order and gradually scales down to O(n²).
Insertion sort is one of the best sorts in situations wherein you know that your data is mostly in sorted order ahead of time.
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.