Question Quick Question on Invariants 

Forum: U Chicago, Com Sci 221, autumn 2000
Re: News Final exam Monday 4 December (Mike O'Donnell)
Date: 2000, Dec 04
From: Ben Johnson <bsjohnso@midway.uchicago.edu>

So it is true that the invariant should still be true even after the last iteration of a while loop? If so, I cannot figure out a binary-search type algorithm where the invariant is left <= middle <= right. If I have the invariant hold, my search only works for an array of an odd size, otherwise say t is at position 4, it will return 5. Here is my code:

#include <iostream>

main() {

int left, right, middle;

 int A[]={0,1,2,3,14,12,11,10,9,8,7,6,5,4,3,2,1,0};

left = 0; right = 18; middle = (left + right) / 2;

 while(left < right)
   {
     if (A[middle - 1]>A[middle])
         right = middle - 1;
     else
         left = middle + 1;
     middle = (left + right)/ 2;
   }
cout<< left << " : " << middle<< " : " << right << endl;

}

Any ideas? Thanks.

Ben


Messages

1. Feedback Invariant still holds at the end by Mike O'Donnell, 2000, Dec 04

to: "Quick Question on Invariants"