avatarDr. Derek Austin 🥳

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

13475

Abstract

ost efficient methods for sorting an array in computer science. For a thorough breakdown, it…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*VjZIPczKGld2lm_W.gif)"></div> </div> </div> </a> </div><ul><li>And <a href="https://rosettacode.org/wiki/Sorting_algorithms/Quicksort#ES6">RosettaCode.org</a> has an ES6 implementation of 2-way Quick Sort:</li></ul><div id="21b4" class="link-block"> <a href="https://rosettacode.org/wiki/Sorting_algorithms/Quicksort#ES6"> <div> <div> <h2>Sorting algorithms/Quicksort</h2> <div><h3>Sorting algorithms/Quicksort You are encouraged to solve this task according to the task description, using any…</h3></div> <div><p>rosettacode.org</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*ieLtmgQC51UH77mU)"></div> </div> </div> </a> </div><figure id="bbf3"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*8XIwPbQwawinBJnR"><figcaption>Photo by <a href="https://unsplash.com/@chadmadden?utm_source=medium&amp;utm_medium=referral">Chad Madden</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="2e6a">Quick Sort (3-way Partition) aka Quick3</h1><p id="50b6" type="7">“PROPERTIES</p><p id="a594" type="7">[❌] Not stable</p><p id="a875" type="7">[✅] O(lg(n)) extra space</p><p id="3d40" type="7">[❌] O(n2) time [worst case], but typically [✅] O(n·lg(n)) time</p><p id="d527" type="7">[✅] Adaptive: O(n) time when O(1) unique keys” — Quick Sort 3 Way on Toptal</p><h2 id="b08f">Quick3 is the preferred version of Quick Sort because it is adaptive.</h2><p id="adfd"><b>Quick Sort (3-Way Partition)</b> has slightly higher overhead compared to the 2-way partition version. Both have the same time bounds, but Quick3 is highly adaptive in the common case of sorting with few unique keys.</p><ul><li><a href="https://stackoverflow.com/users/6692318/atin">Atin</a> implements 2-way & 3-way Quick Sort <a href="https://stackoverflow.com/a/40224415">in his Stack Overflow answer</a>:</li></ul><div id="2f6d" class="link-block"> <a href="https://stackoverflow.com/a/40224415"> <div> <div> <h2>How to write quick sort (Bentley-McIlroy 3-way partitioning scheme) on Node.js?</h2> <div><h3>I'm continue trying to write a algorithms on Node.js like on the book Algorithms, 4th ed. Sedgewick, Wayne. There all…</h3></div> <div><p>stackoverflow.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*GQE4_mhcmV4HOdCp)"></div> </div> </div> </a> </div><figure id="cb73"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*uLtAyk_BXqAWQ0jl"><figcaption>Photo by <a href="https://unsplash.com/@chr_adams?utm_source=medium&amp;utm_medium=referral">Chris Adams</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="e6fe">Bonus: Dual-Pivot 3-Way Quick Sort</h1><p id="6a06">Want to show off in your interview? Or just want an even-better version of one of the best general-purpose sorting algorithms, Quick Sort?</p><p id="0f5f" type="7">“When stability is not required, quick sort is the general purpose sorting algorithm of choice. Recently, a novel dual-pivot variant of 3-way partitioning has been discovered that beats the single-pivot 3-way partitioning method both in theory and in practice.” — Quick Sort 3 Way on Toptal</p><h2 id="8048">Dual Pivot Quick Sort is a bit faster than the original Quick Sort.</h2><ul><li><a href="https://www.geeksforgeeks.org/dual-pivot-quicksort/">GeeksforGeeks</a> explains dual-pivot Quicksort with a C implementation:</li></ul><div id="e597" class="link-block"> <a href="https://www.geeksforgeeks.org/dual-pivot-quicksort/"> <div> <div> <h2>Dual pivot Quicksort - GeeksforGeeks</h2> <div><h3>As we know, the single pivot quick sort takes a pivot from one of the ends of the array and partitioning the array, so…</h3></div> <div><p>www.geeksforgeeks.org</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*-SONRUDGn6KG3Gbw)"></div> </div> </div> </a> </div><figure id="2e9b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*8Y2fnG7Wci8m7lcb"><figcaption>Photo by <a href="https://unsplash.com/@magdaleny?utm_source=medium&amp;utm_medium=referral">Magdalena Smolnicka</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="a87b">Dual Pivot Quick Sort implemented in JavaScript</h1><p id="a9e3">I couldn’t resist including the instructions to assemble this adorable IKEA “KVICK SÖRT” — follow along as he sorts that data:</p><figure id="35ad"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*xqDr2b8QMYxvxgsh"><figcaption></figcaption></figure><ul><li>That illustration 😂 comes from a JavaScript implementation of Dual Pivot Quick Sort by developer <a href="https://github.com/aureooms">aureooms</a> available on <a href="https://github.com/aureooms/js-quicksort">GitHub</a> and <a href="https://www.npmjs.com/package/@aureooms/js-quicksort">npm</a>:</li></ul><div id="ee56" class="link-block"> <a href="https://github.com/aureooms/js-quicksort"> <div> <div> <h2>aureooms/js-quicksort</h2> <div><h3>You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…</h3></div> <div><p>github.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*EFZ2LJrdqy3ZlAHL)"></div> </div> </div> </a> </div><div id="2b18" class="link-block"> <a href="https://www.npmjs.com/package/@aureooms/js-quicksort"> <div> <div> <h2>@aureooms/js-quicksort</h2> <div><h3>Quicksort algorithm for JavaScript</h3></div> <div><p>www.npmjs.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*fITdDDZ9UVlfyv2O)"></div> </div> </div> </a> </div><figure id="a0a0"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*MZ08qI_RQEi6vSHO"><figcaption>Photo by <a href="https://unsplash.com/@lucasmarcomini?utm_source=medium&amp;utm_medium=referral">Lucas Marcomini</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="79a9">Why is Quick Sort considered the best all-around sorting algorithm?</h1><p id="c8ac"><b>Quick Sort</b> is fast, flexible, and optimizable, making it popular even though it is not a stable sorting algorithm:</p><p id="5083" type="7">“Quicksort it is probably the most used sorting algorithm because it’s easy to implement on average, gives high efficiency for large-data applications, it can be optimized for different needs and it’s relatively flexible on it’s input data.</p><p id="2c3d" type="7">Quicksort is a logarithmic-time algorithm, in other words, it has a Big O notation of O(log n)-(more about Big O Notation)- and depending on the way you implement it, it can be up to 2x or even 3x faster than Merge Sort or Heap Sort.</p><p id="85db" type="7">Do note that the O(log n) speed is a best-case/average time, in worst case scenarios it can be O(n2) depending on the implementation.” —César Antón Dorantes in Cesar’s Tech Insights</p><h2 id="bd4e">Why is Quick Sort so popular? It’s on average a very fast algorithm.</h2><p id="1764">I will cover one sorting algorithm that’s even faster later in this article.</p><figure id="76f9"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*EwQ2s3KpXFArePYt"><figcaption>Photo by <a href="https://unsplash.com/@oneminch?utm_source=medium&amp;utm_medium=referral">Dawit</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="ceed">But really — which is best?</h1><ul><li><b>Bubble Sort</b> has the best name. Bubble. Sort.</li><li><b>Merge Sort</b> is the best if extra space doesn’t matter.</li><li><b>Heap Sort</b> is the best if stability doesn’t matter.</li><li><b>Quick Sort (3-way)</b> is best general-purpose choice.</li><li><b>Dual-Pivot (3-way) Quick Sort</b> is the bleeding edge.</li><li>Chrome uses something called <b>Tim Sort</b> (I’ll explain later).</li></ul><figure id="6822"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*yOs5_qXwCN9juVgn"><figcaption>Photo by <a href="https://unsplash.com/@ttrapani?utm_source=medium&amp;utm_medium=referral">Todd Trapani</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="5df1">Which algorithm is Array.sort() in JavaScript?</h1><p id="e77f">This is a surprisingly complicated question to answer, but usually <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort"><code>Array.sor</code>t()</a> uses Quick Sort or Merge Sort:</p><p id="57cd" type="7">“Depending on the type of array, different sort methods are used:</p><p id="e473" type="7">Numeric arrays (or arrays of primitive type) are sorted using the C++ standard library function std::qsort which implements some variation of quicksort (usually introsort).</p><p id="3261" type="7">Contiguous arrays of non-numeric type are stringified and sorted using mergesort, if available (to obtain a stable sorting) or qsort if no merge sort is available.</p><p id="2dd0" type="7">For other types (non-contiguous arrays and presumably for associative arrays) WebKit uses either selection sort (which they call “min” sort) or, in some cases, it sorts via an AVL tree.” —Konrad Rudolph in his Stack Overflow answer</p><p id="1f87">But that is just for Mozilla, as <a href="https://readmedium.com/basics-of-understanding-chromes-v8-engine-c5c8ec61fa6b">Chrome’s V8 JavaScript interpreter</a> has moved on to <a href="https://en.wikipedia.org/wiki/Timsort">Tim Sort</a>, which I explain in the next section:</p><p id="5eae" type="7">“There is no draft requirement for JS to use a specific sorting algorthim. As many have mentioned here, Mozilla uses merge sort.However, In Chrome’s v8 source code, as of today, it uses QuickSort and InsertionSort, for smaller arrays. […]</p><p id="7874" type="7">Update As of 2018 V8 uses TimSort, thanks @celwell. Source” —Joe Thomas in his Stack Overflow answer</p><p id="1f26">So should you just <a href="https://readmedium.com/how-to-sort-an-array-numerically-in-javascript-2b22710e3958">use <code>Array.sor</code>t() in your JavaScript code</a>? Yeah, probably. But that’s not the answer to the interview question! 😁</p><figure id="324a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*EqSXiW3h9etgXcqo"><figcaption>Photo by <a href="https://unsplash.com/@stphnwlkr?utm_source=medium&amp;utm_medium=referral">Stephen Walker</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="2001">Wait, What The Hell is Tim Sort?</h1><p id="3eaa">If you were as surprised to learn of Tim Sort as I was, here’s the low down on the sort used by <code>Array.sort()</code> in Chrome’s V8 engine:</p><p id="a0b1" type="7">“Data structure Array</p><p id="79a3" type="7">[✅] Worst-case performance O ( n log⁡ n )</p><p id="239f" type="7">[✅] Best-case performance O ( n )</p><p id="2344" type="7">[✅] Average performance O ( n log ⁡ n )</p><p id="c663" type="7">[❌] Worst-case space complexity O ( n )</p><p id="5f14" type="7">[✅] [Stable]” — Wikipedia</p><p id="85f3">Wow, if that seems like quite an impressive algorithm, it’s because it is:</p><p id="f649" type="7">“Timsort is a hybrid stable sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.” — Wikipedia</p><p id="2577">Let’s look at a chart comparing Tim Sort to Quick Sort and Merge Sort:</p><figure id="e3e6"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*1CkG3c4mZGswDShAV9eHbQ.png"><figcaption>Source: <a href="http://bigocheatsheet.com/">http://bigocheatsheet.com/</a></figcaption></figure><h2 id="03b0">Tim Sort is a blazing-fast, space-efficient, stable sorting algorithm.</h2><p id="911b"><b>Tim Sort</b> is the algorithm of choice if using O(n) extra space is OK. If memory space is limited, then Quick Sort or Heap Sort may be better choices, as they have O(lg(n)) and O(1) space requirements respectively.</p><ul><li>Developer <a href="https://github.com/mziccard/">mzic

Options

card</a> implements Tim Sort in Node.js on <a href="https://github.com/mziccard/node-timsort">GitHub</a> & <a href="https://www.npmjs.com/package/timsort">npm</a>:</li></ul><div id="2736" class="link-block"> <a href="https://github.com/mziccard/node-timsort"> <div> <div> <h2>mziccard/node-timsort</h2> <div><h3>An adaptive and stable sort algorithm based on merging that requires fewer than nlog(n) comparisons when run on…</h3></div> <div><p>github.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Yszrf4C4U8nW4Bgu)"></div> </div> </div> </a> </div><div id="483c" class="link-block"> <a href="https://www.npmjs.com/package/timsort"> <div> <div> <h2>timsort</h2> <div><h3>An adaptive and stable sort algorithm based on merging that requires fewer than nlog(n) comparisons when run on…</h3></div> <div><p>www.npmjs.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Sgzra_QUpBJGUdnt)"></div> </div> </div> </a> </div><figure id="9ff3"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*jCKjXSL_AHTugZUY"><figcaption>Photo by <a href="https://unsplash.com/@baitman?utm_source=medium&amp;utm_medium=referral">Dennis Buchner</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="3fec">Watch animated sorting at Toptal</h1><p id="e695">The site <a href="https://www.toptal.com/developers/sorting-algorithms">Toptal has a superb animation</a> comparing the 8 sorting algorithms explored here using 4 different types of data. Here’s a screenshot:</p><figure id="f7a6"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*wzNiddoPXm1B7WOJ6shfMQ.png"><figcaption><a href="https://www.toptal.com/developers/sorting-algorithms">https://www.toptal.com/developers/sorting-algorithms</a></figcaption></figure><p id="ef95">For me, it really reinforced the point that Quick3 is adaptive — standard Quick Sort takes forever on the few unique keys data in comparison to Quick3.</p><figure id="6967"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*hLC8_Gdwj2QIBn52"><figcaption>Photo by <a href="https://unsplash.com/@simonkuznetsov?utm_source=medium&amp;utm_medium=referral">Simon Kuznetsov</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="070f">Watch animated sorting at SORTING.at</h1><p id="0d4b">The site <a href="https://sorting.at">SORTING.at also has excellent animation</a> comparing sorting algorithms. Their engine featuring the following sorting algorithms:</p><figure id="dfcf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*OqomvwBxtV3idyEyev5dkw.png"><figcaption></figcaption></figure><p id="f310">I found SORTING.at’s animation to be especially soothing, and it is a great way to compare individual sorting algorithms to each other.</p><figure id="50cf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*twUR79ivgzYgv46z"><figcaption>Photo by <a href="https://unsplash.com/@mustangjoe?utm_source=medium&amp;utm_medium=referral">Joe deSousa</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="24e8">Recap: Summarize 10 Sorts in 60 Seconds</h1><p id="95bd">We covered a total of 10 sorting algorithms in this article. Here is the take-home point for each one:</p><ul><li><b>Insertion Sort</b> is best for small problem sizes or nearly-sorted data.</li><li><b>Selection Sort</b> is best when swapping items is very costly.</li><li><b>Bubble Sort</b> is similar to Insertion Sort with slightly more overhead.</li><li><b>Shell Sort</b> has low overhead and may be good for small data sets.</li><li><b>Merge Sort</b> can be excellent if using O(n) extra space is OK.</li><li><b>Heap Sort</b> is simple, fast, and sorts in-place, but it is not stable.</li><li><b>Quick Sort</b> is a good general-purpose sort with low overhead.</li><li><b>Quick3</b> is the preferred version of Quick Sort because it is adaptive.</li><li><b>Dual Pivot Quick Sort</b> is a bit faster than the original Quick Sort.</li><li>Why is <b>Quick Sort</b> so popular? It’s on average a very fast algorithm.</li><li><b>Tim Sort</b> is a blazing-fast, space-efficient, stable sorting algorithm.</li></ul><figure id="7f8b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*wuNhWKd6TqgCGxyo"><figcaption>Photo by <a href="https://unsplash.com/@paulgilmore_?utm_source=medium&amp;utm_medium=referral">Paul Gilmore</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="9637">Non-comparison sorting algorithms</h1><p id="997d">As a final technical note, I should mention that I only examined <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_sorts">comparison sorting algorithms</a>.</p><p id="07e6">There are also <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Non-comparison_sorts">non-comparison sorting algorithms</a> such as <a href="https://medium.com/@vini.the.pooh/a-better-implementation-of-bead-sort-7ca7352de036">Bead Sort</a> (or Gravity Sort),<a href="https://readmedium.com/an-introduction-to-bucket-sort-62aa5325d124"> Bucket Sort</a> (or Bin Sort), <a href="https://readmedium.com/counting-linearly-with-counting-sort-cd8516ae09b3">Counting Sort</a>, and <a href="https://readmedium.com/getting-to-the-root-of-sorting-with-radix-sort-f8e9240d4224">Radix Sort</a>.</p><p id="910e">Non-comparison sorting algorithms can have a lower bound of O(n), compared to O(n·lg(n)) for comparison sorting algorithms, because non-comparison sorts make certain assumptions about the data.</p><p id="940c">Thus every non-comparison sort <a href="http://pages.cs.wisc.edu/~paton/readings/Old/fall08/LINEAR-SORTS.html">has certain requirements</a> for its use.</p><p id="b8ab">Now get out there and Quick Sort, Tim Sort, or just sort how you want to!</p><figure id="4083"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*BQQW9jVywpLvpHIY"><figcaption>Photo by <a href="https://unsplash.com/@aleskrivec?utm_source=medium&amp;utm_medium=referral">Ales Krivec</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="a288">Further Reading</h1><ul><li>Want to see all these sorting algorithms in one place? JavaScript developer <a href="https://github.com/amhatami/">amhatami</a> has Node.js implementations on <a href="https://github.com/amhatami/Node-Sort-Algorithms">GitHub </a>and <a href="https://www.npmjs.com/package/node-sort-algorithms">npm</a>:</li></ul><div id="9978" class="link-block"> <a href="https://github.com/amhatami/Node-Sort-Algorithms"> <div> <div> <h2>amhatami/Node-Sort-Algorithms</h2> <div><h3>A sorting library for Node.js & javascript made based on well kown algorithmes included : Bead Sort , Gravity Sort …</h3></div> <div><p>github.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*g6tEjeogQP54oOP9)"></div> </div> </div> </a> </div><div id="f60d" class="link-block"> <a href="https://www.npmjs.com/package/node-sort-algorithms"> <div> <div> <h2>node-sort-algorithms</h2> <div><h3>A sorting library for Node.js & javascript made based on well kown algorithmes included : Bead Sort , Gravity Sort …</h3></div> <div><p>www.npmjs.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*fRICj86hptE70774)"></div> </div> </div> </a> </div><ul><li><a href="undefined">Bonvic bundi</a> explains Big-O notation in detail <a href="https://readmedium.com/understanding-big-o-notation-c3245b8112dc">in Better Programming</a>:</li></ul><div id="f97e" class="link-block"> <a href="https://readmedium.com/understanding-big-o-notation-c3245b8112dc"> <div> <div> <h2>Understanding Big-O Notation</h2> <div><h3>The Big-O notation measures the worst-case complexity of an algorithm. In Big-O notation, n represents the number of…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*iQkFjNn02oogc2Yv27-pyQ.png)"></div> </div> </div> </a> </div><ul><li><a href="https://www.geeksforgeeks.org/quicksort-better-mergesort/">GeeksforGeeks</a> suggests some reasons why Quick Sort beats Merge Sort:</li></ul><div id="6aa4" class="link-block"> <a href="https://www.geeksforgeeks.org/quicksort-better-mergesort/"> <div> <div> <h2>Why quicksort is better than mergesort ? - GeeksforGeeks</h2> <div><h3>This a common question asked in DS interviews that despite of better worst case performance of merge sort, quicksort is…</h3></div> <div><p>www.geeksforgeeks.org</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*YIXTFKe3ydg5VxeP)"></div> </div> </div> </a> </div><ul><li><a href="https://www.geeksforgeeks.org/why-quick-sort-preferred-for-arrays-and-merge-sort-for-linked-lists/">GeeksforGeeks </a>shows arrays and linked lists benefit from different sorts:</li></ul><div id="aed2" class="link-block"> <a href="https://www.geeksforgeeks.org/why-quick-sort-preferred-for-arrays-and-merge-sort-for-linked-lists/"> <div> <div> <h2>Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists? - GeeksforGeeks</h2> <div><h3>Below are recursive and iterative implementations of Quick Sort and Merge Sort for arrays. Recursive Quick Sort for…</h3></div> <div><p>www.geeksforgeeks.org</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*G44TmIt5boZj2KXV)"></div> </div> </div> </a> </div><ul><li><a href="undefined">Rohan Paul</a> compares two JavaScript implementations of Quick Sort <a href="https://readmedium.com/quick-sort-algorithm-in-javascript-5cf5ab7d251b">in JavaScript in Plain English</a>:</li></ul><div id="b63e" class="link-block"> <a href="https://readmedium.com/quick-sort-algorithm-in-javascript-5cf5ab7d251b"> <div> <div> <h2>Quick-Sort Algorithm in JavaScript</h2> <div><h3>If you’re interviewing for Software Engineering position, one of the more intimidating questions to deal with is…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*4h-p1NCFaAzQAMyAkNzmpg.jpeg)"></div> </div> </div> </a> </div><ul><li><a href="undefined">Brandon Skerritt</a> discusses Timsort in-depth <a href="https://skerritt.blog/timsort-the-fastest-sorting-algorithm-youve-never-heard-of/">on Brandon’s Blog</a>:</li></ul><div id="bc8b" class="link-block"> <a href="https://skerritt.blog/timsort-the-fastest-sorting-algorithm-youve-never-heard-of/"> <div> <div> <h2>Timsort - the fastest sorting algorithm you've never heard of</h2> <div><h3>Timsort: A very fast , O(n log n), stable sorting algorithm built for the real world - not constructed in academia…</h3></div> <div><p>skerritt.blog</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*1wW6iHBSfbf90NGR)"></div> </div> </div> </a> </div><figure id="3150"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*UbJVxOkbT562EMP82BCP1g.jpeg"><figcaption>Photo by <a href="https://unsplash.com/@pafuxu?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kouji Tsuru</a> on <a href="https://unsplash.com/s/photos/autumn-waterfall?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p id="e36c"><a href="https://www.linkedin.com/in/derek-austin/">Dr. Derek Austin</a> is the author of <a href="https://www.amazon.com/dp/B0BRJDLJ43"><i>Career Programming: How You Can Become a Successful 6-Figure Programmer in 6 Months</i></a>, now available on Amazon.</p></article></body>

Interview prep? Study smart by learning to summarize sorting algorithms

Sorts in 60 Seconds: Speedy JavaScript Interview Answers on Sorting

Developer interviews often ask about sorting algorithms — here is how to explain 10 different sorting algorithms in just 60 seconds.

Photo by Dawid Zawiła on Unsplash

There is no one sort to rule them all

Sorting algorithms can be a confusing topic, but they are a popular interview subject in software engineering jobs at all levels.

That’s because sorts are a great way to demonstrate whether you understand the trade-offs in selecting an algorithm, including computation time (also called complexity) and the space used (often called overhead).

First, some definitions — then we’ll define each sorting algorithm based on these 5 properties:

“The ideal sorting algorithm would have the following properties:

[✅] Stable: Equal keys aren’t reordered.

[✅] Operates in place, requiring O(1) extra space.

[✅] Worst-case O(n·lg(n)) key comparisons.

[✅] Worst-case O(n) swaps.

[✅] Adaptive: Speeds up to O(n) when data is nearly sorted or when there are few unique keys.

There is no algorithm that has all of these properties, and so the choice of sorting algorithm depends on the application.” —Sorting Algorithms on TopTal

Now on to the sorting algorithms: Insertion Sort, Selection Sort, Bubble Sort, Shell Sort, Merge Sort, Heap Sort, Quick Sort, Quick3 Sort, and Tim Sort.

Photo by Scott Webb on Unsplash

Insertion Sort

“PROPERTIES

[✅] Stable

[✅] O(1) extra space

[❌] O(n²) comparisons and [❌] swaps

[✅] Adaptive: O(n) time when nearly sorted

[✅] Very low overhead” —Insertion Sort on TopTal

Insertion Sort is best for small problem sizes or nearly-sorted data.

Photo by Patrick Hendry on Unsplash

Selection Sort

“PROPERTIES

[❌] Not stable

[✅] O(1) extra space

[❌] Θ(n²) comparisons

[✅] Θ(n) swaps

[❌] Not adaptive” —Selection Sort on TopTal

Selection Sort is best when swapping items is very costly.

Photo by Florian van Duyn on Unsplash

Bubble Sort

“PROPERTIES

[✅] Stable

[✅] O(1) extra space

[❌] O(n²) comparisons and [❌] swaps

[✅] Adaptive: O(n) when nearly sorted” —Bubble Sort on TopTal

Bubble Sort is similar to Insertion Sort with slightly more overhead.

Photo by Tamas Pap on Unsplash

Shell Sort

“PROPERTIES

[❌] Not stable

[✅] O(1) extra space

[❌] O(n³/²) time […]

[✅] Adaptive: O(n·lg(n)) time when nearly sorted” —Shell Sort on TopTal

Shell Sort has low overhead and may be good for small data sets.

Photo by Chad Madden on Unsplash

Merge Sort

“PROPERTIES

[✅] Stable

[❌] O(n) extra space for arrays […]

[❌] O(lg(n)) extra space for linked lists

[✅] O(n·lg(n)) time

[❌] Not adaptive

[✅] Does not require random access to data” —Merge Sort on TopTal

Merge Sort can be excellent if using O(n) extra space is OK.

Merge Sort is one of the only sorting algorithms with O(n·lg(n)) time complexity that is stable (equal keys aren’t reordered), and it is simple.

Photo by Jeffrey Eisen on Unsplash

Heap Sort

“PROPERTIES

[❌] Not stable

[✅] O(1) extra space […]

[✅] O(n·lg(n)) time

[❌ ]Not really adaptive” — Heap Sort on Toptal

Heap Sort is simple, fast, and sorts in-place, but it is not stable.

Photo by Kelly Sikkema on Unsplash

Quick Sort (2-way Partition)

“PROPERTIES

[❌] Not stable

[❌] O(lg(n)) extra space […]

[❌] O(n²) time [worst case], but typically [✅] O(n·lg(n)) time

[❌] Not adaptive” Quick Sort on Toptal

Quick Sort is a good general-purpose sort with low overhead.

Quick Sort is a popular algorithm and considered by some to be optimal:

“Quicksort is optimal [because] The average number of compares per element varies within a constant factor of the entropy H.” — Robert Sedgewick and Jon Bentley in their talk Quicksort is Optimal

Quick Sort’s worst case O(n²) time happens with data already sorted in ascending or descending order, but O(n·lg(n)) time is more typical.

Photo by Chad Madden on Unsplash

Quick Sort (3-way Partition) aka Quick3

“PROPERTIES

[❌] Not stable

[✅] O(lg(n)) extra space

[❌] O(n2) time [worst case], but typically [✅] O(n·lg(n)) time

[✅] Adaptive: O(n) time when O(1) unique keys” — Quick Sort 3 Way on Toptal

Quick3 is the preferred version of Quick Sort because it is adaptive.

Quick Sort (3-Way Partition) has slightly higher overhead compared to the 2-way partition version. Both have the same time bounds, but Quick3 is highly adaptive in the common case of sorting with few unique keys.

Photo by Chris Adams on Unsplash

Bonus: Dual-Pivot 3-Way Quick Sort

Want to show off in your interview? Or just want an even-better version of one of the best general-purpose sorting algorithms, Quick Sort?

“When stability is not required, quick sort is the general purpose sorting algorithm of choice. Recently, a novel dual-pivot variant of 3-way partitioning has been discovered that beats the single-pivot 3-way partitioning method both in theory and in practice.” — Quick Sort 3 Way on Toptal

Dual Pivot Quick Sort is a bit faster than the original Quick Sort.

  • GeeksforGeeks explains dual-pivot Quicksort with a C implementation:
Photo by Magdalena Smolnicka on Unsplash

Dual Pivot Quick Sort implemented in JavaScript

I couldn’t resist including the instructions to assemble this adorable IKEA “KVICK SÖRT” — follow along as he sorts that data:

  • That illustration 😂 comes from a JavaScript implementation of Dual Pivot Quick Sort by developer aureooms available on GitHub and npm:
Photo by Lucas Marcomini on Unsplash

Why is Quick Sort considered the best all-around sorting algorithm?

Quick Sort is fast, flexible, and optimizable, making it popular even though it is not a stable sorting algorithm:

“Quicksort it is probably the most used sorting algorithm because it’s easy to implement on average, gives high efficiency for large-data applications, it can be optimized for different needs and it’s relatively flexible on it’s input data.

Quicksort is a logarithmic-time algorithm, in other words, it has a Big O notation of O(log n)-(more about Big O Notation)- and depending on the way you implement it, it can be up to 2x or even 3x faster than Merge Sort or Heap Sort.

Do note that the O(log n) speed is a best-case/average time, in worst case scenarios it can be O(n2) depending on the implementation.” —César Antón Dorantes in Cesar’s Tech Insights

Why is Quick Sort so popular? It’s on average a very fast algorithm.

I will cover one sorting algorithm that’s even faster later in this article.

Photo by Dawit on Unsplash

But really — which is best?

  • Bubble Sort has the best name. Bubble. Sort.
  • Merge Sort is the best if extra space doesn’t matter.
  • Heap Sort is the best if stability doesn’t matter.
  • Quick Sort (3-way) is best general-purpose choice.
  • Dual-Pivot (3-way) Quick Sort is the bleeding edge.
  • Chrome uses something called Tim Sort (I’ll explain later).
Photo by Todd Trapani on Unsplash

Which algorithm is Array.sort() in JavaScript?

This is a surprisingly complicated question to answer, but usually Array.sort() uses Quick Sort or Merge Sort:

“Depending on the type of array, different sort methods are used:

Numeric arrays (or arrays of primitive type) are sorted using the C++ standard library function std::qsort which implements some variation of quicksort (usually introsort).

Contiguous arrays of non-numeric type are stringified and sorted using mergesort, if available (to obtain a stable sorting) or qsort if no merge sort is available.

For other types (non-contiguous arrays and presumably for associative arrays) WebKit uses either selection sort (which they call “min” sort) or, in some cases, it sorts via an AVL tree.” —Konrad Rudolph in his Stack Overflow answer

But that is just for Mozilla, as Chrome’s V8 JavaScript interpreter has moved on to Tim Sort, which I explain in the next section:

“There is no draft requirement for JS to use a specific sorting algorthim. As many have mentioned here, Mozilla uses merge sort.However, In Chrome’s v8 source code, as of today, it uses QuickSort and InsertionSort, for smaller arrays. […]

Update As of 2018 V8 uses TimSort, thanks @celwell. Source” —Joe Thomas in his Stack Overflow answer

So should you just use Array.sort() in your JavaScript code? Yeah, probably. But that’s not the answer to the interview question! 😁

Photo by Stephen Walker on Unsplash

Wait, What The Hell is Tim Sort?

If you were as surprised to learn of Tim Sort as I was, here’s the low down on the sort used by Array.sort() in Chrome’s V8 engine:

“Data structure Array

[✅] Worst-case performance O ( n log⁡ n )

[✅] Best-case performance O ( n )

[✅] Average performance O ( n log ⁡ n )

[❌] Worst-case space complexity O ( n )

[✅] [Stable]” — Wikipedia

Wow, if that seems like quite an impressive algorithm, it’s because it is:

“Timsort is a hybrid stable sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.” — Wikipedia

Let’s look at a chart comparing Tim Sort to Quick Sort and Merge Sort:

Source: http://bigocheatsheet.com/

Tim Sort is a blazing-fast, space-efficient, stable sorting algorithm.

Tim Sort is the algorithm of choice if using O(n) extra space is OK. If memory space is limited, then Quick Sort or Heap Sort may be better choices, as they have O(lg(n)) and O(1) space requirements respectively.

Photo by Dennis Buchner on Unsplash

Watch animated sorting at Toptal

The site Toptal has a superb animation comparing the 8 sorting algorithms explored here using 4 different types of data. Here’s a screenshot:

https://www.toptal.com/developers/sorting-algorithms

For me, it really reinforced the point that Quick3 is adaptive — standard Quick Sort takes forever on the few unique keys data in comparison to Quick3.

Photo by Simon Kuznetsov on Unsplash

Watch animated sorting at SORTING.at

The site SORTING.at also has excellent animation comparing sorting algorithms. Their engine featuring the following sorting algorithms:

I found SORTING.at’s animation to be especially soothing, and it is a great way to compare individual sorting algorithms to each other.

Photo by Joe deSousa on Unsplash

Recap: Summarize 10 Sorts in 60 Seconds

We covered a total of 10 sorting algorithms in this article. Here is the take-home point for each one:

  • Insertion Sort is best for small problem sizes or nearly-sorted data.
  • Selection Sort is best when swapping items is very costly.
  • Bubble Sort is similar to Insertion Sort with slightly more overhead.
  • Shell Sort has low overhead and may be good for small data sets.
  • Merge Sort can be excellent if using O(n) extra space is OK.
  • Heap Sort is simple, fast, and sorts in-place, but it is not stable.
  • Quick Sort is a good general-purpose sort with low overhead.
  • Quick3 is the preferred version of Quick Sort because it is adaptive.
  • Dual Pivot Quick Sort is a bit faster than the original Quick Sort.
  • Why is Quick Sort so popular? It’s on average a very fast algorithm.
  • Tim Sort is a blazing-fast, space-efficient, stable sorting algorithm.
Photo by Paul Gilmore on Unsplash

Non-comparison sorting algorithms

As a final technical note, I should mention that I only examined comparison sorting algorithms.

There are also non-comparison sorting algorithms such as Bead Sort (or Gravity Sort), Bucket Sort (or Bin Sort), Counting Sort, and Radix Sort.

Non-comparison sorting algorithms can have a lower bound of O(n), compared to O(n·lg(n)) for comparison sorting algorithms, because non-comparison sorts make certain assumptions about the data.

Thus every non-comparison sort has certain requirements for its use.

Now get out there and Quick Sort, Tim Sort, or just sort how you want to!

Photo by Ales Krivec on Unsplash

Further Reading

  • Want to see all these sorting algorithms in one place? JavaScript developer amhatami has Node.js implementations on GitHub and npm:
  • GeeksforGeeks suggests some reasons why Quick Sort beats Merge Sort:
  • GeeksforGeeks shows arrays and linked lists benefit from different sorts:
Photo by Kouji Tsuru on Unsplash

Dr. Derek Austin is the author of Career Programming: How You Can Become a Successful 6-Figure Programmer in 6 Months, now available on Amazon.

Programming
JavaScript
Software Development
Data Science
Web Development
Recommended from ReadMedium