Re: binary search with reference to append
- Posted by DerekParnell (admin) Jun 14, 2014
- 1836 views
You have misunderstood.
The issues are:
The logic of the input checks is wrong.
The handling of empty sequences is wrong.
(if you haven't searched you haven't got a position,
setting mid to sp is arbitrary,
something is a bit funny at the caller's end)
The principles of design involved are:
caller contracts to provide valid input.
called contracts to provide valid output for valid input.
I think you are exactly correct with this.
The case where the table is empty, the starting point is beyond the end of the table and the ending point is before the starting point, all should be treated as an error condition and a simple zero returned.
Even simpler would be to drop parameters sp, ep altogether
and pass the slice A[sp..ep] and x.
Yes. This is a much better approach.