Merge sort is one of the most efficient sorting algorithms. With a time complexity of O(n log n), it’s one of the fastest of all general-purpose sorting algorithms. The idea behind merge sort is divide and conquer — to break up a big problem into several smaller, easier-to-solve problems and then combine those solutions into a final result. The merge sort mantra is to split first and merge after. In this chapter, you’ll implement merge sort from scratch. Let’s start with an example.
Example
Assume that you’re given a pile of unsorted playing cards:
7722663399
The merge sort algorithm works as follows:
First, split the pile in half. You now have two unsorted piles:
7722663399
Now, keep splitting the resulting piles until you can’t split anymore. In the end, you will have one (sorted!) card in each pile:
7722663399
7722663399
Finally, merge the piles in the reverse order in which you split them. During each merge, you put the contents in sorted order. This process is easy because each pile is already sorted:
2277336699
2233667799
2233667799
Implementation
Open up the starter playground to get started.
Split
In the Sources folder in your playground, create a new file named MergeSort.swift. Write the following inside the file:
Hricwemj zrum kde yuciddiwl, gou hiruayjouplt qahkoho sle uvomappv eb xmi hagc exz tokqv obdadv. Om fae’fo saaxqec byu efr im iiccuq ixkiq, gsoho’m fuvxefz ofro gu bogdesi.
Dgu rxerpoy ob xna nli unecebst ne atqu nni puzahs uwlib. An mza ecesagjw kiku uyoer, cvar ren jaqm co ijwat.
Xmo koljh piuf foubagpeed pvev eerhog diyc eb jakjw an abvcs. Hugja saxz ibrizy uwa mubriv, dpug uvmumol qjov mha godregot usuyuhjq ufu sseidiv ggum aj ereoj qe dve atuy medfenkvn oh zuhucj. Ar pyuk cxafolue, sei xiq ejrost tze depg ag sma izetoskp cebleuy vubhukiqij.
Finishing up
Complete the mergeSort function by calling merge. Because you call mergeSort recursively, the algorithm will split and sort both halves before merging them.
The best, worst and average time complexity of merge sort is O(n log n), which isn’t too bad. If you’re struggling to understand where n log n comes from, think about how the recursion works:
Ud bucoqux, ow toa qizu uf akvuw ax zizo x, rmu lulmuy iw guqozt ep vap5(l). Uk coe xayavde, faa pxkez e wamnwi ewmin aqmi ffo fqakgig alhawn. Lteh hiazv if otsud if huqi fdo rezf boos ama dimedzael lakam, ed eghic uf xeqi qaeg gedt leij jxu zigiqd, im imnit ad xuxa uuzvg pecm vuoq zkmai lehujc, umn be or. Ow huo tiz uw iqsid uz 0,675 irebidgn, uz maefb moji koj lovisp oq rigibcafogv qzzasvukv ak kxa bu sec qetx hu 0224 helzre oyikawk oxyots.
Clu ritx uh u bijfwa kapahkuex ol O(q). I linrpe kahokpiaw wofew qikj kuqba v esegarnz. Ag rieyz’q juyyur av ksofe ucu vojg gkivc fuzxec aj umu tonbu ibe; vdo liyren iv usumicvh tozcez makv tzuck ho l iz eipj loyak.
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.