CMPSC 465 HW1
Max Menninga
June 2025
1
1.0.1
Problem 1
Inner Loop Invariant
Invariant: At the start of each iteration of the inner loop (line 3), m holds the
index of the smallest element in the sub-array A[i ... j-1].
Initialization: Before the first iteration of the inner loop, m = i. Since
A[i] is the only element considered so far, it is the smallest.
Maintenance: If a smaller element A[j] is found, m is updated to j. This
keeps m pointing to the smallest element seen in A[i...j].
Termination: When the inner loop ends, m holds the index of the smallest
element in A[i ... n]. That element is then swapped into position i.
1.0.2
Outer Loop Invariant
Invariant: At the start of each iteration of the outer loop (line 1), the subarray
A[1 ... i-1] is sorted in non-decreasing order and contains the i-1 smallest
elements of the full array.
Initialization: Before the first iteration (i = 1), the subarray A[1 ... 0]
is empty. An empty array is trivially sorted, so the invariant holds.
Maintenance: During the i-th iteration, the algorithm finds the smallest
element in the unsorted part A[i ... n] using the inner loop and swaps it into
position i. This ensures that A[1 ... i] is now sorted and contains the i
smallest elements.
Termination: When the loop ends at i = n, the subarray A[1 ... n-1]
is sorted and contains the n-1 smallest elements. The final element A[n] must
be the largest, so the entire array is sorted.
2
Problem 2
Initial array:
{29, 10, 14, 37, 13, 25, 19, 2, 7, 34, 16}
After iteration i = 1:
Insert 10 → {10, 29, 14, 37, 13, 25, 19, 2, 7, 34, 16}
After iteration i = 2:
1
Insert 14 → {10, 14, 29, 37, 13, 25, 19, 2, 7, 34, 16}
After iteration i = 3:
Insert 37 → {10, 14, 29, 37, 13, 25, 19, 2, 7, 34, 16}
After iteration i = 4:
Insert 13 → {10, 13, 14, 29, 37, 25, 19, 2, 7, 34, 16}
After iteration i = 5:
Insert 25 → {10, 13, 14, 25, 29, 37, 19, 2, 7, 34, 16}
After iteration i = 6:
Insert 19 → {10, 13, 14, 19, 25, 29, 37, 2, 7, 34, 16}
After iteration i = 7:
Insert 2 → {2, 10, 13, 14, 19, 25, 29, 37, 7, 34, 16}
After iteration i = 8:
Insert 7 → {2, 7, 10, 13, 14, 19, 25, 29, 37, 34, 16}
After iteration i = 9:
Insert 34 → {2, 7, 10, 13, 14, 19, 25, 29, 34, 37, 16}
After iteration i = 10:
Insert 16 → {2, 7, 10, 13, 14, 16, 19, 25, 29, 34, 37}
3
Problem 3
Codeforces handle: mgm6003
2