Note that there are some explanatory texts on larger screens.

plurals
  1. POBinary chop: if list[middle] == key case
    primarykey
    data
    text
    <p>I'm revising algorithms for my exams and I was trying to solve this exercise but I couldn't come up with a solution.</p> <p>This is the pseudo-code.</p> <pre><code>1. int search (int [] a, int x) { 2. // Pre: ∃i:Nat (0≤i&lt;a.length ∧ a[i]=x) ∧ a is in ascending order 3. // Post: 0≤ r≤ a.length ∧ 4. // ∀i:int.(0 ≤ i &lt; r → a[i] &lt; x) ∧ a[r]=x 5. int left, middle; int right = a.length; 6. if (a[0]&gt;=x) return 0; else left=0; //a[left]&lt;x (a) 7. while ((right-left&gt;1){ (b) 8. // invariant: (I1) 0≤ left &lt; right ≤ a.length ∧ 9. // (I2) ∀i:int(0 ≤ i ≤ left → a[i] &lt; x) ∧ 10. // (I3) ∀i:int(right ≤ i &lt; a.length → a[i] &gt; x) 11. // (note: a[i]&gt;x not a[i]≥x) 12. // Variant: right-left-1 13. middle = (left+right) / 2; // left &lt; middle &lt; right (*) 14. if ( a[middle]== x) return middle; 15. else {if a[middle)&lt;x) left = middle ; 16. else right=middle;} (c) 17. } 18. } // left+1=right } (d) </code></pre> <p>So, the code as it is now doesn't satisfy the post condition because for certain inputs (e.g. x = 1 and a={0,1,1,1,1}) the value returned by line 14 doesn't satisfy the post-condition on line 4. The exercise is asking to : "Replace "return middle;" on line 14. by a while loop and return code so that it satisfies the postcondition. Include variant and invariant strong enough to imply the postcondition on return. Hint: Make sure you include to state what doesn't change."</p> <p>I have not been able to find a solution. Can anyone help me?</p> <p>Thanks in advance, VJ</p> <p>EDIT: Ok, thank you both of you for your help.</p> <pre><code>while(middle &gt; 0 &amp;&amp; a[middle] == x){ middle--; </code></pre> <p>} return middle;</p> <p>I chose the variant to be middle. And the invariant to be :</p> <p>0x</p> <p>Do You reckon this is correct?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload