Insertion Sorting

A Sock Sorting Algorithm

Insertion Sort: The most basic, yet most elegant, of sock sorting algorithms.

Sort your socks by inserting each new sock into the sorted list at the correct position.

        
          // Sort an array of socks
          function insertionSort(arr) {
            for (i = 1 to arr.length) {
              for (j = 0 to i-1) {
                if (arr[i] < arr[j]) {
                  // Insert the new sock into the correct position
                  for (k = i to j) {
                    arr[k] = arr[k-1];
                  }
                  arr[j] = arr[i];
                }
              }
            }
            return arr;
          }
        
      

Example Use Cases:

Back to Sock Sophistication