DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question
  1. Home
  2. Tools
  3. Algorithm Visualizer
  4. Insertion Sort

Insertion Sort

Sortingeasy#3

Build sorted array by inserting elements one at a time

Ready

Step 1 of 0

Speed

Input Data

Comma-separated numbers (0-999). Min 2 values.

Algorithm Code

1function insertionSort(arr) {
2 const n = arr.length;
3 for (let i = 1; i < n; i++) {
4 let key = arr[i];
5 let j = i - 1;
6 while (j >= 0 && arr[j] > key) {
7 arr[j + 1] = arr[j];
8 j--;
9 }
10 arr[j + 1] = key;
11 }
12 return arr;
13}
Best

O(n)

Average

O(n²)

Worst

O(n²)

Space

O(1)

About Insertion Sort

Insertion Sort builds the sorted array one item at a time by repeatedly picking the next item and inserting it into its correct position among the previously sorted items. Efficient for small or nearly-sorted datasets.

Time Complexity: Best: O(n), Average: O(n²), Worst: O(n²). Space: O(1).

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.