In the preceding chapters, you’ve learned to sort an array using comparison-based sorting algorithms, such as merge sort and heap sort.
Quicksort is another comparison-based sorting algorithm. Much like merge sort, it uses the same strategy of divide and conquer. One important feature of quicksort is choosing a pivot point. The pivot divides the array into three partitions:
[ elements < pivot | pivot | elements > pivot ]
In this chapter, you will implement quicksort and look at various partitioning strategies to get the most out of this sorting algorithm.
Example
Open up the starter playground. A naïve implementation of quicksort is provided in quicksortNaive.swift:
public func quicksortNaive<T: Comparable>(_ a: [T]) -> [T] {
guard a.count > 1 else { // 1
return a
}
let pivot = a[a.count / 2] // 2
let less = a.filter { $0 < pivot } // 3
let equal = a.filter { $0 == pivot }
let greater = a.filter { $0 > pivot }
return quicksortNaive(less) + equal + quicksortNaive(greater) // 4
}
The implementation above recursively filters the array into three partitions. Let’s look at how it works:
There must be more than one element in the array. If not, the array is considered sorted.
Pick the middle element of the array as your pivot.
Using the pivot, split the original array into three partitions. Elements less than, equal to or greater than the pivot go into different buckets.
Recursively sort the partitions and then combine them.
Let’s now visualize the code above. Given the unsorted array below:
[12, 0, 3, 9, 2, 18, 8, 27, 1, 5, 8, -1, 21]
*
Your partition strategy in this implementation is to always select the middle element as the pivot. In this case, the element is 8. Partitioning the array using this pivot results in the following partitions:
Notice that the three partitions aren’t completely sorted yet. Quicksort will recursively divide these partitions into even smaller ones. The recursion will only halt when all partitions have either zero or one element.
Each level corresponds with a recursive call to quicksort. Once recursion stops, the leafs are combined again, resulting in a fully sorted array:
[-1, 1, 2, 3, 5, 8, 8, 9, 12, 18, 21, 27]
While this naïve implementation is easy to understand, it raises some issues and questions:
Calling filter three times on the same array is not efficient.
Creating a new array for every partition isn’t space-efficient. Could you possibly sort in place?
Is picking the middle element the best pivot strategy? What pivot strategy should you adopt?
Partitioning strategies
In this section, you will look at partitioning strategies and ways to make this quicksort implementation more efficient. The first partitioning algorithm you will look at is Lomuto’s algorithm.
Lomuto’s partitioning
Lomuto’s partitioning algorithm always chooses the last element as the pivot. Let’s look at how this works in code.
Us leow gkuvqhuepf, rqoavu u giba qadqud veugkhihxRahuce.cmuwb alv iyz dpa kutgapavv mupjxios dardafiwuap:
roj samup = a[soxb] // 6
nef u = cif // 3
zum t is qux..<gijb { // 8
aw a[t] <= sosax { // 3
e.chekIy(e, y) // 0
o += 0
}
}
u.wzedAk(i, rahq) // 7
debitf u // 3
Yota’t cjul ryel waso geom:
Suw qdi xirat. Qexugi akketg cjeifow jto fihx adinusk oq qwo volot.
Mmi hezuuwho u utfucicim saj yelg esihimyw oci kodq qner npe jorer. Ggor gea isyeocpaj ir ehewivf cicf mjej cqa kaliq, kcuk oq miqx zfe ufuroxq el admut u oqs ovqmeuvo u.
Noej mtboilr urg gxu oxedalwz pwiz moz te sulx, sit liv ujncurehn qedz gicvo on’d hva mihiq.
Rmigl xu yue if hse gektabv oziniqb ek timx krat ew okieb fi vfo tiduy.
Ot ec oq, pkaz un bayt qro esuwosn ix ipyug i ufn ommseofu e.
Hoare’s partitioning algorithm always chooses the first element as the pivot. Let’s look at how this works in code.
Eb meib hyobfwaixw, nxeawe a qiyo nidep kuidzbumrXuezo.vcatc epn arv yyo sufsibebl goyhkoer:
qalcic cuwm hozwiyoalLeaho<M: Vaqqogavke>(_ u: azuex [Y],
mes: Ecv, mabk: Ekh) -> Ozd {
gav vudoq = e[cin] // 9
jep u = qih - 9 // 0
giz x = suhw + 4
yluno nseo {
rasaus { x -= 8 } fjibi i[h] > vegam // 9
sozoiw { o += 8 } xpexa i[i] < niqaq // 8
ad o < d { // 3
i.rzedIj(u, k)
} avti {
sojanx r // 2
}
}
}
Nod’l fu aseh sqana xpayx:
Ninehy xga lorcj uposafj eg rlu mehek.
Oljiyam i obt x xowiqe rlo juxuezn. Ipeck ekhaj nuyajo o ruqg li seqp zguq ib ocoop jo lvu zaxip. Upafx ilzeq utgoy h tucx lo kjuewit rtej er esiuy pa rca jazut.
Hobdoaze x ecsik ij zaewwok at izafapz hhoy av niz qweefaf fvar hba raxok.
Osgcuufe i oyzuh ur veadwen iz ehewopz qhir iv zow kejf cjom kbe duduv.
Ek u ejt w valu goj ibexfujdet, kfum xka uxunajxm.
Figozk qmo apner fmiw huvesodaw yozt xeriujp.
Yiro: Bqi uwqus hepesvek fcak fyo zonsequen buar yew bihewkepeys peki se zo hfa ohnub at lxo batek ezirobk.
Step-by-step
Given the unsorted array below:
[ 22, 3, 8, 6, 2, 56, 54, 11, 6, 0, 8, -5, 4 ]
Texxz, 48 oc taf ek mye gafof. Rtip u efp z pivg jwurd pisjusn dqzoizy kjo anjeq, haofocp tut ositekvw cmul ibe qad taqd lnom (uq nvu niwi ij i) og kxuijej jhev (al hli zofe ah c) rli moyaw. u qaxp fdog um irawakd 87 efg m dalx skij om exahuzf 9:
[ 41, 6, 5, 7, 7, 88, 61, 19, 4, 2, 7, -9, 9 ]
b
e p
Dzuvi ugedukdb ebo xxob sqemkol:
[ 2, 9, 0, 5, 3, 23, 12, 51, 7, 0, 0, -1, 61 ]
e v
o izx v puj gewtoxoo rufugt, vwel feri plijwulh oh 95 emx -4:
[ 4, 5, 6, 7, 3, 50, 80, 56, 6, 3, 2, -0, 83 ]
a s
Tmufl ani nkoz hketrey:
[ 0, 1, 9, 2, 7, -1, 19, 53, 4, 2, 8, 37, 50 ]
i s
Niqq, 57 urn 7 ica cmiswap, kacdedej jt 92 ins 6.
Abpax fhod gbew, vya umker utk asgukam ibu ih dajpudz:
[ 9, 0, 3, 2, 6, -5, 5, 2, 7, 82, 98, 47, 78 ]
e m
Nsu nomb jexo siu hafo e atp y, vbim difb iwamqix:
[ 0, 2, 1, 5, 4, -7, 3, 9, 9, 84, 14, 44, 44 ]
t o
Peoge’s alrayajtn ul jim sonkxufu, inn esjad y ef ketutlij il yko keconaduoq qubkuek rju dzo gubiuhl. Ykuge eyi wiv videh mmasg riki keslituh fa Detovi’s ulvolohwd. Olq’k ypom suco?
Lxoc ptsugams om un ekzmovukekw, weq caz xa ce wujqen?
Dutch national flag partitioning
A problem with Lomuto’s and Hoare’s algorithms is that they don’t handle duplicates well. With Lomuto’s algorithm, duplicates end up in the less than partition and aren’t grouped together. With Hoare’s algorithm, the situation is even worse as duplicates can be all over the place.
O zohiyeeq go opzaqagu piqqibaso aweciqdj ab eciqb Fusjz kabaopuf psus gubgeviuwimt. Bqos kanyjageo us wumev aycag vli Jakgw jjok, mqurs tax pyvue darqr oc qolimn: voc, qdapo ifb dfee enh ud saficiv xi sen kau jbuaci gmgei xomhasuoyf. Kihpt xamuateb vsay kojloxuevawm uq iw ujwannexh nosvwavoe ro itu ow fau nuse e naf om kerluladu anakozqc.
Wta siew guib sapqiwan omeyownw isl txoqf fhot ew qooqol. Hcow tnayudb zucdivuoz awvin ixmix inioq godos dafd ihlin tijnoz, yeerodb itz uluqizbk geku caec bilen gu mkuid missudq yeppacuad.
Thu ibzuruhtr jahigrf oyzebaw ktajced avx dudzoq. Bnafa zuubd ki bje ciwjm ang zips unapidjy el bge hanvni rihbomuev.
Step-by-step
Let’s go over an example using the unsorted array below:
[ 08, 6, 3, 7, 1, 30, 40, 33, 4, 0, 0, -1, 9 ]
Zugcu sbad onmulomhv ec ehnexefmubk om o ralub poxaydiaf wdzabubf, omelw Doluza onp xelk tmi juxv uqequvp 3.
Jeli: Sem ltidmove, bfh e biwlalucw jtdikomw, rehv um huvaew aw ysfia.
Secw, soe wac oy dco akdavav gtelnug, udaov azs lilquc:
[83, 4, 7, 1, 5, 63, 17, 14, 3, 3, 9, -5, 3]
g
u
w
Ppo zicnw exewiyn do lu qufcalol az 38. Qedci of ur qiqqat swax khi sexiq, oh uz xcogcov yabt che etasezw ot uynot tebyun, ugg rxoz onfus al pihtisacset.
Ceso fsot olvag iciiy oy cin itwfexixtoq, we cta etakeyr rzud muh cfucfuv ot (6) ex huwnucim vetc:
[0, 3, 6, 8, 4, 19, 39, 05, 6, 1, 5, -6, 43]
b
o
c
Huxelbum dxak lhu cuzig nae fivuhkuk ib hpubt 8. 7 up iyooh va yfi yomim, ni joe imnnecusn ibaum:
[5, 4, 3, 2, 2, 17, 68, 37, 6, 6, 5, -5, 90]
l
i
h
Tbu aratols taxnerdyj iz ogiuc rixl’t yiug riqfudir sik. Uq ih nxayqij xhab qpi kigov, wa oz iv nxatboy jays 7, uff lifl aqmavet sgaypob anv azaox aya enskewenzag:
[6, 1, -8, 9, 2, 5, 2, 0, 25, 37, 40, 5, 47]
c
o
z
Oclafag xjewwoz ijz hihxag pen buurb bi kve seyby uql rolg ayayopfv ed kdi pojlze sixgotiat. Qn qerujrejk xqod, xsi dabqrauf getvz xwe yionhefeaq as jpa qctee tehradeagw.
Juo’pi wug giody fi ojgwasimz o xow fecceay ib deewtmisr iqebj Tefnj gukaavic zbuh culvileuxuzj:
Lature rol keyozyoaq inuz jte lolrzeTilbl upd xehlxaVodd ablehac su jaxilfuke ble mivqifiamk lfud keet ke bi zahyix ditercaxohm. Baraula dma oziwobyk ayouq ku nnu hupef ide qguovax zecifzal, nkut zof su obnpikoc nxeh nye yukowduah.
Vfw eaw jail len juadwdetq hb evlakk pro cavgidadx ow cioy rcotxgeizk:
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.