Insertion Sort Visualization

Insertion Sort

Algorithm Explanation

Insertion Sort is an efficient algorithm for small data sets that builds the final sorted array one item at a time. It works by taking one element from the unsorted portion and inserting it into its correct position in the sorted portion. This process is similar to how you might sort playing cards in your hand.

Time Complexity:
  • Best Case: O(n) - when the array is already sorted
  • Average Case: O(n²)
  • Worst Case: O(n²) - when the array is sorted in reverse order
Space Complexity: O(1)

Custom Input

Enter numbers separated by commas. Example: 5, 3, 8, 1, 2

Insertion Sort Implementation


// Insertion Sort Algorithm
function insertionSort(arr) {
  const n = arr.length;
  
  // Start from the second element (index 1)
  for (let i = 1; i < n; i++) {
    // Store the current element
    const current = arr[i];
    let j = i - 1;
    
    // Compare with each element in the sorted portion
    while (j >= 0 && arr[j] > current) {
      // Move the larger element up
      arr[j + 1] = arr[j];
      j--;
    }
    
    // Place the current element in its correct position
    arr[j + 1] = current;
  }
  
  return arr;
}