Sort All the Things

- + - Index - + - Insertion sort - + - Merge sort - + - Selection sort - + - Sally sort - + - Method ▾ - + -

About Array.sort();

This is part 1 of an ongoing project in which I attempt to recreate commonly used algorithms in analog format.

array.sort() — more properly, array.prototype.sort() or array#sort() — is a Javascript method for sorting items in an array. Because it is executed in a browser, Javascript is dependent on browser developers to provide an appropriate interpretation in their code. In the case of array.sort(), each browser makes use of their own preferred sorting algorithm. this means that, while the sort always (or usually) ends up the same, the method used to get there is different.

These very short videos attempt to represent the way the sort function works when array.sort() is called in the browser. While they all return the same sorted array (except for Sally sort), each gets there in a slightly different way. The video above shows array.sort() in the context of a short script for sorting a simple array.

Clicking on "Method" below each video will show the steps taken by the browser, which I captured live by placing some extra code into the script to record the position of each item being compared, and the flag that was returned by that comparison. View the full script here.

As a bonus, I include a method for random sort (Sally sort) using an unpredictable external input source.

Works consulted

  1. Bynens, Mathias (2011). "JavaScript notation."
  2. Pavel (2005-2016). "The MergeSort Algorithm Tutorial."
  3. Rehm, Rodney (2012). "Sorting - We're Doing It Wrong."
  4. Scholz, Florian et. al. (2015). "Array.prototype.sort()." Mozilla Developer Network.
  5. Wayne, Kevin (2004). "Elementary Sorts." Princeton University Course Material.
  6. Zakas, Nicholas C. (2012). "Computer science in JavaScript: Quicksort." NCZ Online.

Fond thanks as always to Tim Menzies, for consultations.
No thanks to Sally Ride, who is a Very Bad Kitty.