Insertion Sort

function sort (arr) {
    const len = arr.length;

    for (let i = 1; i < len; i++) {
        const key = arr[i];
        let j = i - 1;

        while (j >= 0 && arr[j] > key) {
            arr[j+1] = arr[j];
            j = j - 1;
        }
        arr[j+1] = key;
    }

    return arr;
}

How it works

  1. grab an item from a set
  2. insert it in the result array
  3. grab a new item from the set
  4. find where it fits in the result array
  5. insert it there
  6. repeat steps 3-5 until no more items in the original set

Info