Visualizing Insertion Sort

Use the right arrow key to go through insertion sort step-by-step.

Either use the default data provided, or enter your own below.


const data = [10, 6, 1, 7, 11, 5];

// outer loop
// start with 1 index and work your way up
// the value at this index is the value to be sorted
for (let i = 1; i < data.length; i++) {

  // cache value to be sorted
  const valueToSort = data[i];

  // inner loop
  // start with outer loop index and work your way down
  // looking for index at which to insert value to be sorted
  // break out of inner loop after this value has been inserted
  for (let j = i; j > -1; j--) {

    // if inner loop has reached 0 index
    // or if preceding value is less than value to be sorted
    // insert value to be sorted at this index
    if (j === 0 || data[j - 1] < valueToSort) {
      data[j] = valueToSort;
      break;
    }

    // else take value at preceding index
    // and shift it to inner loop index
    else data[j] = data[j - 1];
  }
}