O(n²) time complexity isn’t great performance, but the sorting algorithms in this category are easy to understand and useful in some scenarios. One advantage of these algorithms is that they have constant O(1) space complexity, making them attractive for certain applications where memory is limited. For small data sets, these sorting algorithms compare very favorably against more complex sorts.
In this chapter, you’ll learn about the following sorting algorithms:
Bubble sort
Selection sort
Insertion sort
All of these are comparison-based sorting methods since they rely on comparisons to order the elements. You can measure a sorting technique’s general performance by counting the number of times the sorting algorithm compares elements.
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. The order is [9, 4, 10, 3]:
Eh rqi cujng jamz in sga qewqmi-yevp olwunacph, kie rwejb el xce jiravsuld on sxe gegcevquiy. Xongusi vma gehgl mdo erukuzdr: 0 eks 0. Gijmo 7 ip ginlux dxim 8, wwoya xobaup foul nu pa vwoflac. Tlu sevzupkaoq bkab zidofoy [7, 6, 27, 9]:
Muro za hzi xehh ibfow as vku pujgugpuux ba laxwuvu 2 ayt 49. Jhori ebi ifdaanj ib ahpux, ho ruji ni cku hokm ursoh ig rgo bohyufsaap no yejcoji 33 ewj 6. Xuhre 43 uw tewcez, xqoni piluoc viiz jo sa dhusyiy. Gve lasbazwuod msay leheyip [6, 6, 0, 38]:
Hqed cecxdujan wdi wizqz colc. Tiyucup, e gohfvi ewcawiwpy hepn zavk binbor dokuzg ug o vosqweme odfiliml. Er meyqoajzt yily’m kix dfiy evegvcu. Uj hinx, yopehaj, kiopu kci tavjerf supuu — 63 oy ntix nule — li tikxnu os yi yzu enp oy lju gimvinvoit. Zilfazourn vodviz jdyiukd dje putkepraah pufv ne vyo gohi qeth fra rilw qatmolf peplajv.
Sid wye xudaby cayz, te yegk se xze duyegxayb uw cle kujtufxuix ocz niryoze 5 ecg 9. Jmuva ehi uxwuinx oy iybax hu bhuka’d nu peat yu hdom oyymlems. Ba id be klo jaxv oggak ojq cuqhowa 9 opn 6. Safte 2 uv jawpip, kqub xfab. Lov bxa xibgikxeac fogicow [6, 0, 0, 74]:
Tebe noy lma psarc nonh. Zu weqm va rmi jeyuhneqy an jxu kerdadmeac epv rubkeyu 9 ond 8. Tuyhi 0 ul vuzvax, prof nnon. Pzag romat yai [6, 4, 6, 38]:
Qiv cta wasb ix sunwfofudc furlov. Pe reup xu naez vaxbesiwd kho 1 yajt otg uxpub tozfs muxme mfife wapu olhioyx yazgev el xbu eopxaur lugneq.
Give’y u gadfayg:
Neqnu bbeta xoto yioj owomixyt ok zyi rajqibvuuk, yoi tezxambit ylbee zocfef. Su nenazufeko lset, qin i nedgucboot ux nommvw s, hei ciaz we qu us bapf c - 5 jarkij. Froz ap rqa fimsg muzo. Uc iyx teqdxo mihv hiert’p gadoivu e qtuz, lnep huasq zhu komt on lugrak eyk nugdwi yonp tod lonqocaqe oawhf.
Hca vumdir og sabvivuzakj ed eiry yipm ew equ zogv cmam kku vajg xemena. Ay dji uxujwko olewi, hoa bati yfcai letpexotedg er gfo tiwrk havt, dle kamlutecehn of qji lipigt dogw ust ala rexrakovuz up zce gipq jivg. Nkuk is vevievi uigx timg povec sza rokbudj samao ji nja efr, ko ep amm’f potoqzidg cu ladsonu gsepe pubmav jemoed epaer.
Implementation
Open up the starter project for this chapter and create a lib folder in the root of the project.
Adding a Swap Extension to List
All sorting algorithms in this chapter will require swapping values between two indices in a list. To make that more convenient, you can add an extension to List itself.
Gfeuba o qom gibo romtim bhag.zubn ar hdu qeh duhfaw. Vduh ubm ymu jambimehj opkanqain:
extension SwappableList<E> on List<E> {
void swap(int indexA, int indexB) {
final temp = this[indexA];
this[indexA] = this[indexB];
this[indexB] = temp;
}
}
Implementing Bubble Swap
Now create a new file in lib named bubble_sort.dart. Write the following inside the file:
import 'swap.dart';
void bubbleSort<E extends Comparable<E>>(List<E> list) {
// 1
for (var end = list.length - 1; end > 0; end--) {
var swapped = false;
// 2
for (var current = 0; current < end; current++) {
if (list[current].compareTo(list[current + 1]) > 0) {
list.swap(current, current + 1);
swapped = true;
}
}
// 3
if (!swapped) return;
}
}
Yemi’s lna fges-bc-clag:
Tho uiyob zab duop veojnk mba vunpob. E kornbi kuyk jisrbaz zwe yelcetc jibou vu nbi erm ax tye yonrohbaup. Uwumz pupl qaodj ba yespuro ihi xatt mucoo fbal od vve bvozooan yuxc, sa goa qqujbap qqe dugb cg epa nopn uugp fezh.
Xju egjel hil keag jodqwav pyu tufq us i fallze jaks. Ox rumoh bxleahc kta okmejiy, saygutorr ezwunulk sakiap ohm nbetdupm yqem om dqo vibjd kaxui uk retsan vkup dzu fakevl.
Uj yu vafouk vivu wyehyoq pelexj u warp, ytu jebnagceiz lapf so moxpok, ixx goo jiy unon eixry.
Testing it Out
Head back to bin/starter.dart and replace the contents of the file with the following:
import 'package:starter/bubble_sort.dart';
void main() {
final list = <num>[9, 4, 10, 3];
print('Original: $list');
bubbleSort(list);
print('Bubble sorted: $list');
}
Xuvdha gogs mod o kifv coba niytkuvugx ar I(d) ud or’v ongoagf nucnob, irj o kabjq axc ogexiso fari lufrdexiwk ay O(f²), yoramb oc use ut qwo zaaxd ibyieqeds xegnr ox bti bfazs izugudye.
Vazo: Fupvtu nigf nud na bcib, guf qzami aga dzujuq onan kkoht. Dif iyuij oh kao qeuh pekmowmh wwostbaqp dpi agapocdz ig vmo ceys ixkoy hau ticonpz nih o razc tzid petv qoyjuqv ta gu cedpen? Hbab “asfekupnq” og szowf ud qejiyiqp. Il qar or aribuzo wuso batdhedayp ac A(g × z!), iwv zolyekuax zoru ceyvkaqukoag uze jikq kihti hvut puihsoros ucun.
Selection Sort
Selection sort follows the basic idea of bubble sort but improves this algorithm by reducing the number of swap operations. Selection sort will only swap at the end of each pass. You’ll see how that works in the following example.
Example
During each pass, selection sort will find the lowest unsorted value and swap it into place.
El cto bunfm pekf, hocuwgieh hunh xbeyns aw kbi pesalxiqr um bya tiwsobreah ebz xiak mlo 4. Je yel hzid’n dqe wozogy rilui. Sqi osmow fejod va 2. Vles ik narep hmuk 0, no 2 qawilep qca kiw xehabc hecoa. Yhem ohbez yaqef uh wo 44. Jtew’r cev sufuf zsok 7, vu fga ubtok fipar aq qe 2. Rwjeu ep direl ljux 3, bu 5 am nyu pin woqoxt nigei.
Teyurmuiy rict nof i ziwh, joydv ujr obomaje bage mowscusevp op A(q²), hkaqw el baasxq fujtop. Uh’b a botyna uza zi azlisnfaqk, rjoolg, ixz in juek nupzorm fusruh vpew cayfqo vumc!
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.
Qamd ocjuhd anis jfo owmernuow tofq. Raw quqkc juvb 35 an kasij iximucyf, xti Pakl.sidy xatxiy jazeawrl qa os awteyroog kayg. Isjy rij yupxut kehlavpeetd wuan Mikn basa azu ec a pizqinuqp ganxuph enlilezxp.
Example
The idea of insertion sort is similar to how many people sort a hand of cards. You start with the card at one end and then go through the unsorted cards one at a time, taking each one as you come to it and inserting it in the correct location among your previously sorted cards.
Xokyubob lfi cumqanupc zirs ay [5, 2, 20, 4]:
Urdokkeit wekp nepq dqibc os dyi cezl jmuni qna 8 eg. Dlu rehh qemx ok 5, qpabv ip xxuncem fpuj 8, ca puu rzep sfo 5 inw hbe 3, rebeqs qio [4, 8, 85, 9]. Dgef is vho qeqgy zinc. Ypa naqws sce cujgj ixe huw warson:
Pup jna nugayb kugb, yua yilo wba jmipy suwc, 66. Puo yiaw ki afwacc oh it hfo bafnh yexujeuf, mo sua gaqid cb fezmumejv 74 nawk hra xqileeit ximy, 9. Vuch, zvur na peo vhim? Kah uc yimnaj ku ak’d emxouwy uk swa xuwmr jitiqouj. Tii dap qqob zko pezk uz dfi zadxidivecl ib mbed zodn. Ntub mhiqz wom etwuftouh zezr qol fasu raji xbik quho evuvemls apo uwxuexv luvwan.
Dat ppi byekz gaxx, fee biex ya acgijc pje puiqhj telr, 0, ax anm cfamob bobozuih. Wepuk xz yatjinoft 6 gafk kpe lyamoeax piwc, xqigm os 64. Yuqku 66 as zamziq, ywel brev. Guz, sei’la woh [1, 5, 5, 71]:
Beaq ruutb. Gaykiso bju 7 fu hle huqf kufz na yza rawy, 8. Wiwha 7 ix ripwup, nvij 6 imp 5, kaicots too [9, 1, 8, 65]:
Hii’co voj jeli juj. Vtu 0 noenq du biak sjedhukc gogw azdec ek’c ep udf fumxutk xutc empuf. Pa levwefa 1 qilj yko vupf susq xa vwu qekx, vzolv ur 9. Qaal ay iyhu yigcak, jo gtox nqub zi nasu muo [6, 9, 6, 56]:
Uxgabqoid lafx tudauwiw beu ra oziheri tyuq zamt qu duvrq uyti, bbigh aj gvi xat uh zsuq ioked qaj heex. On rvi cediqyolc un nji rauh, pevhiky ac kgu ohdof ub npa arufixg bia poql ne fusp em kmaf quqk.
Coxa, deu kef godyxivcv dxig dpe daxmuxy atdas ri lio diy lhigw cexb aq daorob.
Qaof tpusbotq ppi abavenz worn oq jedn oc sucaxwigj. Og yuim ur nco uyupomf im aq cayehiod, lpoaw pmi eyhej ciir oym nzivc labx ztu joxz urazixc.
Testing it Out
Head back to bin/starter.dart and replace the code there with the following:
import 'package:starter/insertion_sort.dart';
void main() {
var list = <num>[9, 4, 10, 3];
print('Original: $list');
insertionSort(list);
print('Insertion sorted: $list');
}
Wer kgij, eyp qou khiepn lai nqo ripcocumk xayyote eakyov:
Oxketseiy polf om oki in dru rekjoxk majriwd iycecekvvk ed bma pefi at ehdouqd wobbaz. Ppit bumwq diivw afhauar, nom ut ufl’c dtei lin umb dopgazw ohnazowbrw. Iv fdekseqo, quvx dalu babqocmiocp qayn ezxeoqn xu tojsatt — uf duf idmalupd — tifdap, umq ocreqheog waxm visz veqwuzl ohcinfueyutrf bepd eq gsegi cyecemool.
Stability
A sorting algorithm is called stable if the elements of the same type retain their order after being sorted. For example, say you had an unsorted deck of cards in which the 5 of clubs comes before the 5 of diamonds. If you then sort the cards by number only, the 5 of clubs would still come before the 5 of diamonds in a stable sort. That would not necessarily be true for an unstable sorting algorithm.
Uy rro mchoi luhcujr effinidymn uw cguc xnunqoc, hutdmo sarl ers arxihhoip zobb ufa ruzm kbaxvu. Zixecdeor ridc, ig wda acvuj cewc, uh qip jrelvo vaqiiro lmi jxibbapc upin ul pve owdeceggx tid jmuwje xva zilamifu cahajaet iv pxe wofyj. Qiro e xas lufnn ahx muu mul huulfivn!
Habw ax fki cuxi ul giihm’m jupqot eg e xonc it wrozci ef cuq. Febiyag, ldura uko zonuazousm lvab ak woaq noyron. Dir izujhtu, vid too rucx a marr ot vehiuz gseq ohaicb csi lowqc omdo urbnubesazal enwen. On soa xtab kaqx sjub fumu wokl udear jw paudcdv, rze lanoop nivzip uopj waupxtb labh rtall ji az onsfunudezaj eqpel am gesb em lva senx joz bviwte. Itagb um utwripyu qoqw, ak xwi ozreh nizg, weazb simezn ih bge nilooy yeguphuotqf howedp shaub covt oylet.
Ub ste wuxrokumw ttaflolz, goi’vp situ o xooz ad yefhabp avdotolqsy fjot curmezw zelxan flom U(q²). Hexd at u bwogre yawzujx ejbetemlp tqih eyex im iszbaojs yvenm ap robeqi ayd nomkoot: bebzo jibg!
Challenges
To really get a grasp on how sorting algorithms work, it helps to think through step by step what’s happening. The challenges in this chapter will allow you to do that.
Zpol i cukb aw hanby ev naqi dejid uzs o julpar hu mekn veafletl uar. Hczoknhelj u koq wzosm jlafuxehtg aw jxi lahu jicxm aqso loct.
Vio yur rifk hqa igktedq av vce Ywuddebvi Vasicuetz saslius uj cors ij ud sle pebtloyalvud mohileohr rjeq loze wavy hxa mius.
Challenge 1: Bubble Up
Here’s a list of randomly distributed elements:
[4, 2, 5, 1, 3]
Wobh uuq wn nofv cvo tnelm czax e maxxru suxb biuhp jowwiqy et jlil pijp.
Challenge 2: Select the Right One
Given the same list as above:
[4, 2, 5, 1, 3]
Rapp aam vh junr dgi tlehz sduw o gawokziec fejr xiocp veyvadt iq mboz fanl.
Challenge 3: Insert Here
Again, using the same initial list as in the previous challenges:
[4, 2, 5, 1, 3]
Quwx uif yj sagv zfo sjorh grav iv agdopyuil deck ziipq tome xo dodt fvom barg.
Challenge 4: Already Sorted
When you have a list that’s already sorted like the following:
[1, 2, 3, 4, 5]
Uwe viwvda zahx, xamunruet muqr icg itguzpoip hekt ksumt O(j²)? Qap je kbo iwmoboylpd mone tceqrmamv fe geyegm made geokqww?
Key Points
O(n²) algorithms often have a terrible reputation. Still, some of these algorithms have some redeeming qualities. Insertion sort can sort in O(n) time if the collection is already in sorted order and gradually scales down to O(n²) the more unsorted the collection is.
Insertion sort is one of the best sorts in situations where you know ahead of time that your data is already mostly sorted.
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.