Sorting algorithms

Sorting algorithms put an array in order based on some notion of comparison. They're some of the most fundamental algorithms that every computer scientist must know. Here we introduce three: insertion sort, quicksort, and merge sort.

Quicksort


Quicksort is a sorting algorithm which works using the idea of pivots. The pivot, represented in red, is randomly chosen from all our elements in the array. Once that pivot is chosen, we move all elements less than the pivot to one side, and all elements greater than the pivot to the other, and finally swap the pivot into the correct location. Repeating this recursively eventually sorts the array.

Mergesort


Mergesort is a sorting algorithm based around the idea of a zipper. In a zipper, we combine two strands of zips by interlocking at regular intervals. In mergesort, we merge adjacent subarrays taken at regular intervals, with the catch being that within such a merge we always choose the smallest element from each array to add to the merged output. Recursively doing this up to the largest length (the whole array) outputs a sorted array.

Insertion Sort


Insertion sort is perhaps one of the most basic sorting algorithms alongside selection sort and bubble sort. It works much like the way you sort cards in your hand when playing poker: you keep a sorted set of elements and put unsorted cards into their rightful place in the sorted set, repeating this action will indeed yield a sorted array. Although slow compared to, say, Quicksort and Mergesort, it is simple and surprisingly fast on smaller sized inputs.