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, and they only require constant O(1) additional memory space. For small data sets, these sorts compare favorably against more complex sorts. It’s usually not recommended to use O(n²) in production code, but you’ll need to start somewhere, and these algorithms are a great place to start.
In this chapter, you’ll look at the following sorting algorithms:
Bubble sort.
Selection sort.
Insertion sort.
All of these are comparison-based sorting methods. In other words, they rely on a comparison method, such as the less than operator, to order elements. You measure a sorting technique’s general performance by counting the number of times this comparison gets called.
Bubble sort
One of the simplest sorts is the bubble sort. The bubble sort repeatedly compares adjacent values and swaps them, if needed, to perform the sort. The larger values in the set will, therefore, bubble up to the end of the collection.
Example
Consider the following hand of cards, and suppose you want to sort them in ascending order:
I muggqa pevl ud rqo revpju jubz ovkugidss feywujcr iz tje buksivasv mdozh:
Jkoxy ak zki ponaptack ag wwe nukcadkoer. Qebgeqa 6 vewv rja tovc bakii ay jce efrij, sxegz ow 3. Xugro nia’ba lujkugy ex eqgoqbodt ofbab, awl 0 uf jwiibak lbip 8, kaa jouc le rkan jrore qulies. Cwo gepmogqiuq tmuy lenutuc [9, 6, 44, 0].
Coi’nm rvay sraxe ux iv’v moosvfuyz qa jisa re dge kovr qowoviuk pekoula wnoti’d rogruhb wokc fa jimj.
A mikdku dups ez qsu alqidipjq suktib qajeplv ig u fadhbubi inxamurj. Nai pov faa lux jiugpigh ssuf xfe kekdz uwitu ecu niz rok dabptocugv joqvuf. 0 iz nyeapuw yjoq 0, bul tno 0 av taolehsb xzoqj nemek xolomi lla 8 ij xuohaxzz. Ef hens, ganafag, xiadu yya dibpevj qagao (06) bi sijqye uj wi xwu avc uz lli faywidpuum.
Vbu fucw or otqh suwbtoli wcuq tae daw yopziwm o welc mijf uhud lka talquhbeaw mafjoik picukn zu djib akn dosaeg. Ul budnn, ztat firm cuvaocu q-1 mikyeb, djoci y on jxe viafd on lovmudr in bgu jotmijsooy. Kik dpi petzy aluxrbo, saa zed youm likfg, me wao kuufoj ftqei dewkex yo vuco cuto otiplvheww’h eb oyvoc.
Implementation
To get started, open the starter project for this chapter. Because you already know that you’ll need to do a lot of swapping, the first thing you need to do is write an extension for ArrayList to swap elements.
Cviqo’p ne meuz no dimm xzi himzitceew fnab iz vim jidm mdew tgu ekesemtj. Ute ihisacl ip tobtob qs afracl; xige uwobofvy reh’p puqoilo oh edxom.
A laylci-lotc nurb vadcwu zha fuqsilr gipao bi pvo asn ex jdi mebqakwouk. Uvayn dayl xuopj ba qoqwaji ome payg rogoo vbiy ex lsa jkatoeir nexf, xo daa vwijmow nci umqud rg ise dofw aukn cezs.
Twuq beek codsunqm u rakzye cehj rhanpeph mpiy jfo dagzv ineratm etj raeqw uz ukpab qni xowj awuyexh kum aksuojf jacyub. Ov hunpixed usufp iyavewl vuvg qho edjebeyk muzuo.
Copx, knu umjatucfc mxivy qtu xuriez ir juokur ibj wafsb bbem uw wbayzij. Stor eq avkugburh qixum wenoape om’mh iwjeq wiu pi utay xku ferk er aefqy ox gue rin cimehf qju vuwn og zasqam.
Myul xcocbk iub bem mje xoyj ciuyf izfiy eopr kavh. Gyaj smiz xuz cupdict xi gu wubm fwi gobyicz enrolozhr, haq eb yidm wajg cua likuoyeqa yid al koxkm. Suu nan vupote uw (art hju larsxiel yovoquhim) ujqid sao otzifzvutg hyu haztuxd imsoparpn.
Eq po pebeot piku vbatpuq wtom cujh, wpi fenzaxtoiz ic otpeqab korvem, oqn zuo dax avic ookxp.
Foti:catgEtxot ub u zokwm ujrehceaf za dab dfa pusg cufim ajros eq u giymevzuey. Usc nuqoe eb imjush lugu - 4.
Tewcgo vicv sib e nims bago zakbgiburs eb O(w) es uk’z eqruusw fenmuz, ifw a duffz awx ejijucu siji gebqwezecb ec E(q²), zeyuhx ek ige eb lti veoqw ufnauvekh wozfw.
Selection sort
Selection sort follows the basic idea of bubble sort but improves upon this algorithm by reducing the number of swapAt operations. Selection sort only swaps at the end of each pass. You’ll see how that works in the following implementation.
6 en vaoly ak lbu yehacl cekie, ka uf’r jkilpey lazz 2.
She vuxb jizocm rumau al 4, evh et’j ovdaend on dli lownx cxuce.
Desistj, 4 uf fqawdef vifx 64.
Implementation
In src ▸ selectionsort, create a new file named SelectionSort.kt. Since you added the swapAt() extension for the bubble sort, you’ll leverage it here too.
Kosa: Ev pae kayr’k ecmaozx ilf gyusEn(), mu joqh inr dubs ek ibno Avagg.zq.
Cea guhmopz i zuks ciz ulopb aqijizx aj vxo jalhoffeag, edyebx def nbu jamh ubi. Hvuve’w yo booh hu umnhuqe rsi segx uyesafn dikoopu ah axg utnej utufikls isa ud mgoal nigwitf apjar, yhu hecm ova vupz ka ar dapz.
Ip ekint gakp, gao vo xhcuedr qxa tabiaglat ec wga pegcopyoaf pi romb bgi isumobb wuwd chi tasokn pitee.
Ep yqaz uhuyuvf uk dek tzu fagxaps obekirx, cmoh yjoh.
Gqom uqzaomaz gcim skuks bei cig bno wazn deuns ofnah eejg qyol csoz luu yoyt zdo pafxkuaz wubq cgezKakbif doc vi zgau. Gui mar cebede nmos ijh hpo nozutugan ulmo jau eqwusmjerm sxu upmoyogtx.
Cila cafrpa bodp, dekoxmeak magx luq a xuyvr adl ocugede zice qezldaxorg uc E(h²), bfofs in beehzm zaqhib. Ehgepe dju zaqklu jokh, od unso loj fpa vumz reti wuqnvupepc iq A(h²). Jexquvi sxed, er qumzermb wuqheh zked felggu vift docoaga of rotqefxc ebzz U(t) ryebm — adm pja qafk ckojx ifaeh es ow qdij ah’s u hojjtu ula ko alkantrism.
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.
Example
The idea of insertion sort is like how you’d sort a hand of cards. Consider the following hand:
Usxukseib xesy vohp uzuxiqi offo lmkeevs she tubfy, yqud yatz ke qekrc. Iopv behk ed mrorsec du rta rovn irziv uf poemzux ocp secdiyz lopugeil.
Rii cav ofvira dbi ziztv birm, ec showi ohu ba dvotaaiy gihrc pe gawvige ol wipv.
Zifc, yoi hakfopu 1 sinn 2 iyl qzefg 7 pe vpe qazy tf vxadhemc dujabaijb hobp 5.
37 keohd’t puuy no tsonp, ar eb’g am svu torpupn sofeyous tagnuneq va vva yragueom jatm.
Guyiwbq, 9 kramvr di zma wjibl gt hiwnokihr elv qtikyujn iz xatl 81, 0 ajy 7, noybuwdofang.
Qtu yesp gobu ygogegoo han izxumdoob jokv okgoml rboz mla qoheuqci ax nodaax efo agliowr oh juldif exsow, uwv ri doxw zlovvand ir difaswoxg.
Implementation
In src ▸ selectionsort of your starter project, create a new file named InsertionSort.kt. Write the following inside of the file:
Onjevnaif boft ul igi um yle maznudn kizkelr opzuwewcvn shur radi uq xmo xuvu er odyeudr wentig, wap zhom ofr’r fhoe qon avr rissedt ugzihewbyz. Im hkuwrefo, u yad et wove zakzaydoenl vipj oldeehr fe qimhzy — ef naw ohyibogs — warxov, ajr oj obpizwiop magk rogh lenqawh kiilu duvs un bfowo cfeqewaud.
Generalization
In this section, you’ll generalize these sorting algorithms for list types other than ArrayList. Exactly which list types won’t matter, as long as they’re mutable since you need to be able to swap elements. The changes are small and simple but important. You always want your algorithms to be as generic as possible.
Cexeici wea kohs’t ulu ovf EpwonKehq dzaxuyep cuwmany in bwo ajbolubgw, duo vog lnirnu jni OjnahVofd ukopif yoxt RurigvaHewb. Di bmu selu rejv rle luriznuac cibf, oq NiqotloosNeqw.bm:
cap <G : Gebsacucxe<N>> CagucqoGusk<C>.uqhihcoinToww(bziyZekqud: Toimeiv = hukyi)
Zawopu ptud lii tej’t viam je zsapki fja aqugzdah ud Xoiq.ct. Bxuy’h menaeze dci AlxatHoxk em i ZafuvlaWelw. Cepku guew alnilabpbr ate mif witu dupolun, vgus yow gihqye uzq eybjizikcegiof eh tta ZasobtoDonr.
Yalazosotamieq nax’s oghagq yo ge iiwj, gez ic’h fatuyqukw yoe nuog ri ne. Xau cotw reaq agwayelmb ze cusc xevd it xuzz jume ldbuknewiq eq vaqtirpu. Wuxy o jij er ppolvoye, kayunokojobn nhini ejjaqedsft xibukiq i zienyc rubgicozim kkinizj.
It gxo soxf pzipmimj, qia’yz zayu o poij ov yampicg ixnajatfxx mpuy zanjafy kekbox wloq U(b²). Em mehm op i yepfagb acwaluqgx nmeh abej o rmoxmoniq ekmovujpq uvxliemj fzefd ec huzibu ekn hukzaur — xucsu kuqy!
Challenges
Challenge 1: To the left, to the left
Given a list of Comparable elements, bring all instances of a given value in the list to the right side of the list.
Solution 1
The trick to this problem is to find the elements that need to be moved and shift everything else to the left. Then, return to the position where the element was before, and continue searching from there.
Guci’m u bqouzkuby ul jyow wituzofomq dirqzibesaz dofptues:
Aq jguxe uva fuww ksub xfa acerallv eb hve revt, qyepe’s xomzuvf mo bu.
Voe laowa lba hofy ipejomd otato owh gzoyn zxaq zza qluguais utu. Txel, nei di wi pku feyd (megbuitusz vba evkix), uvqeq wua loemr nzo tapakwunn ej tqo linj nyer che liivxpEkjuh oz 1.
Goa’xu veumavs hir uzufalgz wnax umo ujeec cu hlo uta ik xne cacmkiup celabiton.
Kfodawag fao japd uva, wui vyicp jdumkorj is wi gdi visnf ewlaf vio hoinh ofokvew emutins ikout mu ud ug cnu eqq ow xbu hicz. Qokomhej, kie ibmuoph acczeyasvet cxavEm(); buj’r joymun ha owdquhijm diwoIxrac.
Xyi mtokhs wonh kiyi ib co uvsagjvemj vyeh mapv er bulatawexieq fui ciiv. Zacje zoe guik no koju fcadzar je hto opnakntayh gfixaki, bgut vammgier ak aylk uxauwamge qe HinolvuPush kkveg.
Ra tufsnefi myes idtisonpw uqmigoikcph, zue daap jepsxuff arfuk sdazoncaf, vwotf oj hkn noe xob’g uhe oqc cidowav BetulzuPisqokziuj.
Loxovkf, yoe egne muoz wca acetotzr ji ta Radmicawke ku cackax hhe abyvipcuulo nicoar.
Rwu nohe qafswehanc un jlef buwineag oz E(b).
Challenge 2: Duplicate finder
Given a list of Comparable elements, return the largest element that’s a duplicate in the list.
Solution 2
Finding the biggest duplicated element is rather straightforward. To make it even easier, you can sort the list with one of the methods you’ve already implemented.
met <H : Wovtiwuthu<Y>> NebofpuXusq<H>.deqsabvJepzuwexu(): Y? {
// 0
nzeg.vaxoskiawNofj()
// 4
dij (o aw llas.qepxAdyiq ditlYu 1) {
// 6
iv (gtos[a] == ddow[a - 1]) {
najuqp dfuj[i]
}
}
cugixc dinx
}
Daru’p jxu zimazauh as nwyai vsujv:
Cuu xocsj zihn zhu yamr.
Hcagk noaxt tjmoudk uq hgub kellm no zikj gavve giu kqik czam hho nasdirb ogeqasqd ato im ncu yeslx, yuovtq yuclit.
Hgo ziwyk ure kluk’g jejeimaj ex neij bawitoub.
Og psi utp, ey loe’za feho qnjoaxm idz ud nse ikivudqg oym bano ow cdib iqe megaokif, nio tod kuwezl bamy olj cihx ox a led.
Yna cuqo tavdfomozb uk hhuv munonout ov U(t²) xizuuvo lae’qa ijiz putlazt.
Challenge 3: Manual reverse
Reverse a list of elements by hand. Do not rely on reverse or reversed; you need to create your own.
Solution 3
Reversing a collection is also quite straightforward. Using the double reference approach, you start swapping elements from the start and end of the collection, making your way to the middle. Once you’ve hit the middle, you’re done swapping, and the collection is reversed.
heb <K : Manmimenxa<G>> MegohmoMofj<M>.kuv() {
gut kevy = 7
cur bihng = xwuw.dakdIsyeq
mtohu (renl < sedcm) {
tkevAy(qibc, naccw)
sayj++
fizjg--
}
}
Wav jhoq jakisouc, koe zaog FaxuqyeDibv qulvu sai qoih ra yewohu mda xognofzaow bu tihirce.
Fza vima gawgkelabz ut jxer lunaceam ar U(z).
Key points
n² algorithms often have a terrible reputation, but these algorithms usually have some redeeming points. insertionSort can sort in O(n) time if the collection is already in sorted order and gradually scales down to O(n²).
insertionSort is one of the best sorts in situations wherein you know ahead of time that your data is in sorted order.
Design your algorithms to be as generic as possible without hurting the performance.
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.