I am trying to find then loop invariant of selection sort
Pseudo code
SELECTION SORT (A,n)
for i= 1 to n-1
smallest=i
for j=i+1 to n
if A[j]<A[smallest]
smallest=j
exchange A[i] with A[smallest]
My answer for the loop invariant, is that the subarray A[1:i]
is always sorted and consists of the smallest elements of A[1:n]
,however the official solution mentions that instead of A[1:i]
, it will be A[1:i-1]
.
Here's what I fail to understand, if the invariant is A[1:i-1]
,then when i=1
at initialization, we have A[1:0]
. How does that make any sense? What does the subarray A[1:0]
mean?
Here's the link to the official solution