Implementation
Let’s code insertion sort. It’s straightforward with nested loops.
Complete Implementation
function insertionSort(arr) {
const n = arr.length;
for (let i = 1; i < n; i++) {
const current = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
return arr;
}
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
current = arr[i]
j = i - 1
while j >= 0 and arr[j] > current:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = current
return arr
Try It Yourself
🟨 JavaScript Insertion Sort Implementation
📟 Console Output
Run code to see output...
Code Explanation
- Outer loop: Starts at index 1 (first element is already “sorted”)
- Save current: Store element to insert
- Inner loop: Shift elements right while they’re greater
- Insert: Place current element at correct position
- In-place: Modifies original array
Edge Cases
- Empty array: Returns as-is (loop doesn’t run)
- Single element: Returns as-is (already sorted)
- Already sorted: Inner loop rarely runs, very efficient
- Reverse sorted: Inner loop runs maximum times, O(n²)
Optimizations
- Binary search: Use binary search to find insertion position (reduces comparisons but not shifts)
- Early termination: Stop inner loop early if no shifts needed
- Sentinel: Use sentinel value to avoid boundary checks
Recursive Version
**Simple and efficient:**
• Easy to understand
• No recursion overhead
• Standard implementation
• O(1) space
**Alternative approach:**
• More elegant conceptually
• O(n) space for call stack
• Slower due to recursion overhead
• Not practical for large arrays
What’s Next?
Now that you can implement it, let’s analyze its performance and complexity.
Progress 71%
Page 5 of 7
← Previous
→ Next