l = -1; u = n;
while l+1 != u
m = l + (u-l)/2;
if x[m] < t
l = m;
else
u = m;
p = u;
if p >= n || x[p] != t
p = -1;
We assume x[-1] < t and x[n] >= t and n >= 0 in the above code.
The above code is a modified binary search which can return the first occurrence of the integer t in the integer array x[0..n-1] instead of returning a random one.
My question is like this:
Why do the above code always halt? Can anyone explain it or prove it?
Thanks,
Because on every iteration, the gap between
landuhalves, within the constraints of integer arithmetic. All sequences of (positive) integer halving must eventually reach 1, which is the termination condition.