Insertion Sort Algorithm
InsertionSort(A, n)
for i = 1 to n-1
key = A[i]
j=i-1
while (j >= 0 and A[j] > key)
A[j+1] = A[j]
j=j-1
A[j+1] = key
Time Complexity Analysis
Best Case (Already Sorted):
Outer loop executes n-1 times, while loop performs only one comparison each iteration.
T(n) = c1(n-1) + c2(n-1) = O(n).
Average Case:
On average, each key is compared with about half of the sorted elements.
Comparisons ≈ n(n-1)/4 ⇒ O(n²).
Worst Case (Reverse Sorted):
For i-th iteration, the while loop executes i times.
Total operations = 1 + 2 + ... + (n-1) = n(n-1)/2 = O(n²).
Space Complexity
Only one extra variable (key) and loop variables are used.
Extra Space = O(1).
Summary
Best Time: O(n)
Average Time: O(n²)
Worst Time: O(n²)
Space: O(1)
Stable: Yes
In-place: Yes