Insertion Sort
Sortingeasy#3Build 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).