Skip to content
dreamcode
dreamcode
Map
Merge sort
Lesson 40 of 48
+15 XP on finish
JS ALGORITHMSChapter 8 · JS Algorithms

Sorting Algorithms

The built-in sort is fast, but writing a sort yourself teaches how algorithms think. Insertion sort grows a sorted section one item at a time: O(n^2), simple, and quick on small or nearly sorted arrays. Merge sort splits the array in half, sorts each half recursively, then merges the two sorted halves: O(n log n) every time.

Worked example

How it reads

  • merge always takes the smaller front item of the two sorted arrays
  • mergeSort splits until each piece has one item
  • The pieces are merged back up, level by level
Cloud tip: In real code, use sort with a compare function. Writing your own is for learning and for special cases.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Finish insertionSort without calling sort. It should print [ 1, 2, 5, 5, 6, 9 ].

Press Run to check your work.