In binary Search algorithm, the upper-bound element is array.length-1, then how can I find the last element of an array?
If the lower-bound and upper-bound for element of an array of length 8 is 6 and 7 respectively, then my mid element coming out as:
mid=(6+7)/2 i.e. 6 in java
It really comes down to using the right compares with the correctly chosen midpoint. For instance (without variable type declarations),
will give you the index of the leftmost element that matches val (even if it is the rightmost element in the array). You don’t need to explicitly check the last two or round up rather than using the built in integer truncation.
However, if you want the index of the rightmost element that is equal to val then you need to change the < operator to > and mid should be given by
It’s as simple as that.
Edit: One more thing, I looked at my code that I use for this and realized that you have to to also change the the calls to binsearch to end up on the rightmost element. I’ll just post the full code for this (which I should have done in the first place). Here’s a binary search to find the rightmost element equal to the val.