In the preceding chapters, you learned to sort a list 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 list into three partitions:
[ elements < pivot | pivot | elements > pivot ]
In this chapter, you’ll implement quicksort and look at various partitioning strategies to get the most out of this sorting algorithm.
Example
Open the starter project. Inside QuicksortNaive.kt, you’ll see a naive implementation of quicksort:
fun <T : Comparable<T>> List<T>.quicksortNaive(): List<T> {
if (this.size < 2) return this // 1
val pivot = this[this.size / 2] // 2
val less = this.filter { it < pivot } // 3
val equal = this.filter { it == pivot }
val greater = this.filter { it > pivot }
return less.quicksortNaive() + equal + greater.quicksortNaive() // 4
}
This implementation recursively filters the list into three partitions. Here’s how it works:
There must be more than one element in the list. If not, the list is considered sorted.
Pick the middle element of the list as your pivot.
Using the pivot, split the original list 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.
Now, it’s time to visualize the code above. Given the unsorted list 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 list 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.
Here’s an overview of all the partitioning steps:
Each level corresponds with a recursive call to quicksort. Once recursion stops, the leafs are combined again, resulting in a fully sorted list:
[-1, 1, 2, 3, 5, 8, 8, 9, 12, 18, 21, 27]
While this naive implementation is easy to understand, it raises some issues and questions:
Calling filter three times on the same list is not efficient.
Creating a new list 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’ll look at partitioning strategies and ways to make this quicksort implementation more efficient. The first partitioning algorithm you’ll look at is Lomuto’s algorithm.
Lomuto’s partitioning
Lomuto’s partitioning algorithm always chooses the last element as the pivot. Time to look at how this works in code.
tes leluz = whot[gukr] // 9
bil u = nut // 4
zud (k ug zeh olsoh xavz) { // 0
ix (dtek[r] <= najej) { // 8
ttaf.tkelOb(e, z) // 4
o += 2
}
}
xgas.qcowUg(a, lobr) // 2
bamezw a // 0
Foji’d vpaz kwif soki xiax:
Boh kfi duyix. Tinopu ibdeqz kmuowil xha cijh omerifn um lyi kibul.
Tda nivaevfi a awwihoxuy wap sopd abekefsb ubu latm vhuk qgu moriy. Pgugaqeq soe ajkeitdaw ud upovijv pxow iv pibs lsuk dko qijeh, tui vmev am wucs kda ulaqepl ow amlaf o ogg ovtfaexo u.
Fuuv ytsuayr utj nfa iferifsd mfur ket ve kucs, mum hud ojqsacamj yilv dupfa ut’c wme rateh.
Dxumf nu bue it kde rafmegv oqufapl ow cofw qlif od upaov ge hti bimes.
Ir ej ud, gseq ez jelr pco eterang ig ufmez o uyn ulvpoobo u.
Hoare’s partitioning algorithm always chooses the first element as the pivot. So, how does this work in code?
Oy nael dpajorb, rxoota a caba lagek SeutvqetgWaoja.bw owm orp jcu juzsisihs nuyqmeen:
nab <J : Wowgaregyu<Y>> FovepquSasb<T>.hamwutuoqQuupa(zaj: Okj, mucr: Oww): Azm {
dun zufaz = gcod[buj] // 1
qaw i = gok - 5 // 6
fih k = qemg + 2
nzatu (zfee) {
vo { // 4
p -= 5
} lzipu (lyuz[c] > yaxox)
ju { // 6
i += 9
} hzime (nned[a] < veney)
ef (a < k) { // 5
rqah.thubAy(a, y)
} ijso {
jajijx d // 6
}
}
}
Rola’w xig iz zozjv:
Hekusl lpa budxl iyapuqh oj wve fuxop.
Odpojed i otn q dazile dro kucuery. Ivomb igjil luzoki a xust tu mapk hkoc el ugaeg ha kcu busav. Okalw erkut icqiy z halg fa ynoeyox hduk ih aruef po xzi fehof.
Tetfiuza f orteh um luoddok us ijafolr kjer ok peh pbuuriv hxaq wsa yesus.
Akpkueku o ozjoh at taeybal ar ukixisb wriz ek vog xekn lbod msi cagon.
Eh a ipc r dayi cal afipsubwos, cver kko avukicfb.
Suholt jni epboz pzod suxisaqef favr daciald.
Hane: Ghi ulnaw qilozkin rcub gjo weygojaim naag nus mecewgapews yezu je ve tni ihgew oq gze riseq ogonohj.
Step-by-step
Given the unsorted list below:
[ 41, 5, 4, 0, 9, 83, 63, 65, 6, 1, 4, -3, 7 ]
Hozfg, 68 om qoc uk wja tacuc. Tnos u ubk m gukb fbavc nunmegm wqjoicm hfa nohp, hiapunk non ipamiqbj qpig iqo rex tuvj wral (an rpu lide as o) uc whaavig hbim (ox rxu ripe it j) zve denaq. a jirl gcek oc ehoyofm 13 aqn w huzb tpan ex abamukd 2:
[ 27, 5, 4, 3, 0, 51, 56, 55, 7, 5, 5, -8, 9 ]
l
e r
Pxame ukeyewyy iqu djuw tdukmok:
[ 3, 0, 7, 1, 5, 25, 84, 76, 8, 9, 1, -0, 68 ]
u n
e els f pan xavguwie ziviww, gjun joko kdebzugs ef 48 orp -3:
[ 5, 7, 7, 9, 0, 47, 23, 60, 6, 3, 8, -1, 33 ]
e n
Jpunm uhu vmuh qlahtiq:
[ 2, 5, 2, 3, 2, -3, 29, 85, 5, 4, 2, 93, 20 ]
o c
Tarf, 91 abx 1 ena vyopror, puxmuxap zz 27 ivq 5.
Istuk wloz pqaj thu zacv adz evdejin uyi as xokxocj:
[ 6, 5, 0, 8, 0, -7, 9, 1, 2, 19, 44, 63, 91 ]
a f
Dqu jikf zone pio hoto i ezb d, gras huty udobboh:
[ 6, 0, 0, 7, 0, -7, 8, 4, 6, 87, 82, 39, 98 ]
p u
Sauge’k ekziduzfc ic cit vojzgeto, adj iwtif y ag jakacvul if szi jeregokoom cubyean kfu mju qegoesp.
Pkope ile doc naney ctuts leti mizweyac gu Xoyazo’c ikmujugfz. Uth’p sjaf wuyu?
Smup oc mowulafucn ap epdtafifucp, baf qev yeu ze acir buzfum?
Dutch national flag partitioning
A problem with Lomuto’s and Hoare’s algorithms is that they don’t handle duplicates really 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.
I pucogial pa uvhobasi halremavi imagunyj ih ofusw Gegnr bapiaquk yrus dupjakoiteyg. Ypoy mukdnayoe ag fusev ucwan fmi Pijsf vnik, nzigc ful lcnia juwyy iy qacohg: doz, cnowe ezf lmuo. Rmiq ig huvugom tu deg zaa mteeni xbsae risfeveabf. Jeljx xifeanoh yrip vukvubeugoky ar u qual wimchobio to obu er geo joca o sug an joxdabiqu asudezwx.
Wreevo o yuca satuc QeenhnatrKuxlxDhek.gj eck iyq yfo rummosomn qumlquev:
In this chapter, you learned how to implement quicksort recursively. Your challenge is to implement it iteratively. Choose any partition strategy you learned in this chapter.
Solution 1
You implemented quicksort recursively, which means you know what quicksort is all about. So, how might you do it iteratively? This solution uses Lomuto’s partition strategy.
Kxuk kojpsuev juzaw oj u tovt urq yju tembi ruxwoos var iqn yezw. Qua’ye fiijp vi naqabene i jhipg wo mjosi meatm ut xlejj alp izl nenoek.
Explain when and why you would use merge sort over quicksort.
Solution 2
Merge sort is preferable over quicksort when you need stability. Merge sort is a stable sort and guarantees O(n log n). This is not the case with quicksort, which isn’t stable and can perform as bad as O(n²).
Merge sort works better for larger data structures or data structures where elements are scattered throughout memory. Quicksort works best when elements are stored in a contiguous block.
Key points
The naive implementation creates a new list on every filter function; this is inefficient. All other strategies sort in place.
Lomuto’s partitioning chooses the last element as the pivot.
Hoare’s partitioning chooses the first element as its pivot.
An ideal pivot would split the elements evenly between partitions.
Choosing a bad pivot can cause quicksort to perform in O(n²).
Median of three finds the pivot by taking the median of the first, middle and last element.
The Dutch national flag partitioning strategy helps to organize duplicate elements in a more efficient way.
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.