Skip to main content

Sorting

3 lessonsAbout 18 minutesIntermediate

This part of the DSA Tutorial runs from Sorting in JavaScript through to QuickSelect: the Kth Element Without Sorting. There are 3 lessons here, and working through them takes about 18 minutes at a steady pace.

It follows on from Backtracking, so finish that first if you have not already — the examples below assume you are comfortable with it.

Each lesson below says what it covers before you open it. Read them in order the first time; afterwards this page works as a index you can jump back into when you need to check one thing.

  1. 1Sorting in JavaScriptArray.sort compares as strings by default, which is the most common sorting bug in JavaScript. Learn the comparator, sort stability, and what the built-in sort actually costs.
  2. 2Sorting Algorithms You Should KnowMerge sort, quicksort and counting sort in JavaScript — how each works, what it costs in time and space, and why the built-in sort is still usually the right answer.
  3. 3QuickSelect: the Kth Element Without SortingQuickSelect finds the kth smallest element in O(n) average time by only recursing into the half that matters. JavaScript implementation, and how it compares with a heap.