Step-by-step solutions to build your algorithmic intuition.
Key Idea: At each step, insert the current element into its correct position among the already-sorted elements.
[5, 2, 4, 6, 1, 3][2, 5, 4, 6, 1, 3][2, 4, 5, 6, 1, 3][2, 4, 5, 6, 1, 3][1, 2, 4, 5, 6, 3][1, 2, 3, 4, 5, 6] ✓
FIND-MIN(A, n):
min = A[1]
for i = 2 to n:
if A[i] < min:
min = A[i]
return min
Time Complexity: $O(n)$ — we look at each element exactly once.
Loop Invariant: At the start of iteration $i$, min holds the minimum
value of the subarray $A[1..i-1]$.
Initialization: Before the first iteration ($i=2$), min = A[1], which
is trivially the minimum of $A[1..1]$. ✓
Maintenance: If the invariant holds at iteration $i$, then after comparing $A[i]$
with min and updating if necessary, min becomes the minimum of $A[1..i]$.
✓
Termination: When $i = n+1$, the invariant tells us min holds the
minimum of $A[1..n]$, which is the entire array. ✓
Best Case: [1, 2, 3, 4, 5] (already sorted)
Worst Case: [5, 4, 3, 2, 1] (reverse sorted)
Answer: $n$ comparisons
Explanation: In the worst case, the target is not in the array (or is at the last position). The algorithm must check every element, making exactly $n$ comparisons.
This gives us a time complexity of $O(n)$ for Linear Search.