So here's the dealio I had a question on my most recent exam dealing with the concept of loop invariant in a function, and I am wondering if the solution provided is something known among the community.
Question
In the implementation of Selection Sort below, insert the loop invarian that accurately describes the sorting of the array in the proper four places. The invariant may either be in the form of a comment or an assertion.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void SelectionSort(int A[], int numberOfItems)
{
int minIndex;
for (int i = 0; i < numberOfItems - 1; i++)
{
minIndex = FindMinimal(A, i, numberOfItems);
Swap(A, i, minIndex);
}
}
|
now the places where the invariant was supposed to be placed were the 4 blank lines, this is how the solution looked.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void SelectionSort(int A[], int numberOfItems)
{
int minIndex;
//A[0..i-1] is ordered
for (int i = 0; i < numberOfItems - 1; i++)
{
//A[0..i-1] is ordered
minIndex = FindMinimal(A, i, numberOfItems);
Swap(A, i, minIndex);
//A[0..i-1] is ordered
}
//A[0..i-1] is ordered
}
|
(first, why isnt it [0..i] instead of [0..i-1])
I understand that it works for the part inside the for loop, but for the parts before and after i is not able to be used, therefore eliminating the ability to use assertion.
The exact question i'm looking to get answered is whether or not it is a known thing that when thinking about the invariant outside of the loop it is okay to use i?
PS I have found 1 source that also does this, but no where else, im skeptical.
http://firner.com/weblog/article/selection-sort
Thanks,
Ginger