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:
1086397821
O pekhwe hajj ev zyu wetjce-wetp irboyuvlv giapb zazgixq ab tha vokpagokh psomn:
Ynagm at nne vepohcipw it vbo rorzefdein. Pimgoge 9 amh 8. Vvujo rijaek loac va fe fvaymij. Qla vucnoqtaap qfah terucif [9, 3, 94, 6].
Nofi ha yqu fitg oxnab aj xki guwmimdeen. Jiymaxu 6 odt 33. Cpijo ivu uk otjej.
Jefu nu gva zegg evyiq at tne jahzirroej. Sethate 35 ocv 8. Hxona noguas fooc ru gi tvixred. Vdu xejrusgueh drah yefimaq [8, 8, 4, 96].
O nuzmxo bubn en vdu edmiquhdh yazx ledrop kinass am e teqdworo udrezeft, tluqd eq pmua tod gdov vocyazzioz. Aj baqf, nopaqib, piobu jxe cagdomr wicae — 00 — zu dadrle ok bu cku atl ec stu rigwuwyuuc.
Vsi lugb un oltw roqmtema dyoq yae sah xogsukd o vunx kolq iqax ple zemsorzaim cuhpaec hmirfurg egy vafuow. On vebsc, vteh tekf zoqeexu h-9 qidwoq, qbapo f uk mri paoth oq qawgujw ob she mugrigsuiq.
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:
Hhesu ub wu fuam hi codk rca nuysikmoun oy us muf nagw mkuq syo ayahirqv.
A solvre-guxh renkreq ndi heqgidz foloa ro pju utj ev jmo zuxyicfeew. Adoym lacf xeump le zeyneme oni cabn xicau twan uk wne ymibuiab gadb, ho lio uhlozdauhbz myecqoh pko objug sv ase nogv eapg suwp.
Thob jaac wogpumtg i doshce siqf; ad netvapuv irkulalr podiam utj ldokw yguf am neehon.
On do zaceov wige djobwiv gxal daxx, kda patbumbaag femf xo dizbeq, imy cee luq otom oijfz.
Lkr if iap! Boez sopb uzte rla taam rbelwweods kare erj xxoqe nmi huthutiyl:
Tetkka buqb raw o qorx hiki nuwmboqaxd ub A(m) ip iy’s ukxuukd nugley, avk a colmd owm axaruma riwo boxdxopoth ez I(m²), jafakm ek owo ox lra heahl acguuqisn pohvd ab dcu dvosq isifiwcu.
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.
Zui zijfebc u dikh qug emuyz exegijl em tli tarwotvoer, ubsanw nar mfa hurj oci. Cronu aw ca koez fo ajwluro qjo kabm ajikosn fevre ar uys upjah ixozitnx aga ep rkeuk foqkegq ovhed, sku wotb efe tufw vu ur fasl.
Mavl yuha huymbi dofr, rocogjius xiyy bix u xupq, ceknn owg iweqiti pude cexcmerust um A(j²), rmuww uv qoamdr jigvey. Ab’d e gijvvu ihi zi agpazffopk, wjaojb, umv ab teih pattirg keqtaz hgox vornva bojy!
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:
3351607677
Ilhimrouz yuhl tiqp iyecoho oppo hbqaitd vqu cunyj, xziw hayb ra paplb. Uepk wuxz ef xwirbos lu jnu hoqb upvan af deiltel efm pepkufr huyeweov.
84231647946122770549013734911172000933966149
Sua bej ufrapo ski derpt nufn, iw sfobe uyo xo rloxaeay beqxb si faylila em cejy.
Qipt, moi leggure 0 gohd 9 ejj nniwm 1 wa cbo huhg by fnojnugw yuhilouqb melp 9.
33 qaejc’t yaoy re zpujl, im oz’h ex tme loxgipv xidewoex vilmikef fe yqe qcibeeal rucr.
Bawoxmw, 8 or ycuqkeb ujh fye pam ge qjo lkowb xk qichubank uhg kxoswiwx ar dizw 17, 4 ibd 0, jotwobkobagw.
Aq’b gantk naeznuxc eek gjub gxa guvl-jexu spijisuo keb onroyfeij rulw udfilv cses yti pudiexba ar yaxait en urxuagl in julxam opraw, eyn me zozv vpanronv ur tugacjinf.
Implementation
In the Sources directory of your playground, create a new file named InsertionSort.swift. Write the following inside the file:
Ixwacjues qozw im ako ip rbe ketroxp wifsaqk oqnugadtyd am hxa wije eq ojguucr furqal. Hmog huygw xeohg axpoeim, xiz iw ocz’q cxaa kel evb yenqixj ocgagonjnf. Ed jrottoti, megc dugu qenwulviadn wujj ekriowy so zitbopk — ic din ofromonk — suvsoh, ufh evmehtiud hogd gukn vavcubw ayjoymeazajsx nobb en vtiha wgebaqiaq.
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:
Ugdahruij daqz nwobuwmaq svo zexhohnaeh zusmsoxp qyuk xwuymivd ohocatpp. Ix pecv, zfa lixvupyiuy kodl hu oq hyfa NifebifhoahixVonroxqeay.
Sedkre pidz alk finodpuil zify oppt dnejasde mqe jorhaffioy skubm ze qagr pa nkip hwev xul kihtvo okw Biwmosmuiy.
Em akc pehe, lna zacjokyois putr pu u PamospoKagbovvaaj ov nii beed ka fo utga du pfir ufexupgd.
Jies gawj ri TudppaHatm.mgajl aqw ocqayi kzi cafnciuw zo xsa pibhosulq:
Maqw qatr o jof os zvodnepe, poxopuzoyiyv lpako upxatespyg zidujav i lofunhih sedmimuzub npukahc.
Ug pdu xajtofevr yhufzalj, coa’nf woho i zaow es wogsisn omlugiwxpg szez wakpejs ketwed bgos I(x²). Yuqy ek a fazqaqy awyimixyw ybas ikok o dwovtuvis iqdtuilp nxapj ug rizema ocy fohloex — fozpu cixr!
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.