Foundations
Linear Structures
Hashing
Array and String Patterns
Recursion, Search, and Sorting
Problem Solving Patterns
Algorithm Searching
Sorting Algorithms
Array Algorithms
Grid Algorithms
Linear Structure Algorithms
Hashing Algorithms
Recursion and Backtracking
Greedy Algorithms
Tree and Heap Algorithms
Graph Algorithms
Dynamic Programming Algorithms
String Algorithms
Math Algorithms
Keyboard ready
Space plays. Arrow keys step. R restarts.
LAB Insertion Sort Lab
Sorting
Problem shape
Beginner
4
8
15
16
23
42
Core idea
Grow a sorted prefix by inserting each new value into its correct place.
Step 1 / 5
Problem shape
Sorting Beginner
Insertion Sort
Welcome to the Insertion Sort algorithm lab. Grow a sorted prefix by inserting each new value into its correct place. Use it when: Use for small or nearly sorted arrays. The time complexity is O(n^2), best O(n), and the space complexity is O(1). The pseudocode is: for i from 1 to n - 1 key = a[i] j = i - 1 while j >= 0 and a[j] > key a[j + 1] = a[j] j-- a[j + 1] = key As you practice, track the state that changes and the condition that makes the algorithm stop.
Time
O(n^2), best O(n)
Space
O(1)
Pseudocode
for i from 1 to n - 1
key = a[i]
j = i - 1
while j >= 0 and a[j] > key
a[j + 1] = a[j]
j--
a[j + 1] = key 1.0x