Sei sulla pagina 1di 3

Q.

1 Algorithm # 01 Loop invariant Loop invariant is the property of the main loop of an algorithm which holds at the initialization of the loop, maintains the condition during iterations and when the loop terminates the property yields correctness.

Loop invariant for Algorithm # 01 As each iteration of the outer most for loop starts, the sub array A[i+1n-1] consists of the smallest elements, found originally in A, sorted in descending order and the sub array A[0i] has no element which is not from A[n].

Proof Take an array A with n=5, as an example


8 3
8

12

9
8

Initialization: At i = n-1(i=4), the sub array A[4+1n-1 to the right of i is empty. It is reasonable to say that an empty sub array is ordered and the left over elements are from A[n] forming A[o4], thus the loop invariant is followed. Maintenance: After execution at i=4, now i=3
8 9 12 5 3

The sub array A[44] has only one element originating from A[n] and an array of one element is always sorted. None of the rest of the elements are not from A[n] forming A[03], thus the loop invariant is followed. After execution at i=3,now i=2
8 9 12 5 3

The sub array A[3n]has only sorted elements, originating from A[n] and the rest of the elements are from A[n] forming A[02], thus the loop invariant holds. After execution at i=2,now i=1
12 9 8 5 3

The sub array A[2n]has only sorted elements originating from A[n] and all the leftover from A[n] form a subarray A[01], thus the loop invariant is followed.

After execution at i=1,now i=0


12 9 8 5 3

The sub array A[14] has only sorted elements from A[n] and the rest of the elements form A[00], a subarray of A[n]. Thus the loop invariant is justified.

Termination Now i=-1 and the loop condition becomes false


12 9 8 5 3

The sub array [0n-1] has only sorted elements which leaves an empty array of A[-1-1] at the left hand side. The empty array has no element which is not from A[n], thus the loop invariant still holds.

As the loop has been terminated it is evident that the loop invariant, i.e. the sub array A[i+1n] always consisted of the smallest elements, sorted in descending order and found originally in A, and there had been no elements in the subarray A[0i] which is not from A[n]. thus the loop invariant was consistently held.

References
Some notes on correctness proof.ppt by R.Paul Weigand, George Mason University, Computer Science department Cs/Math240: Supplemental handout on selection sort by Roger Jenke

Potrebbero piacerti anche