If the array contains multiple elements with the specified value, there is no guarantee which one will be found.If you ask me, this is a painful restriction. Binary search is pretty commonly used, and it's not that difficult to think up a version of binary search that finds either the first or the last of the multiple occurrences. I'm a bit surprised that they didn't do that - it's not a very large piece of code.
Anyway, it turns out that you can use a binary search to pull off something like this, with practically no difference in code size. In fact, it actually seems smaller than the conventional implementation. The difference is presumably that you only check for equality right at the end, when the interval is just one unit in size.
Here's the stuff I hacked up. I had a slightly weirder version up a while ago, but it didn't work for certain inputs. This one seems to be perfect.
// Returns 0-based index of the key if it exists, -1 if it's not in the list.
public static int binarySearch(int[] list, int key)
{
int n = list.length;
int lo = -1, hi = n-1;
while(hi-lo > 1)
{
int mid = (hi+lo)/2;
if(list[mid] < key)
lo = mid;
else hi = mid;
}
return list[hi] == key ? hi: -1;
}
Suggestions and challenge cases are welcome. Feel free to try and break this code.
Side issue: The Blogger edit window goes nuts whenever I try to edit this post. Something about the code is conflicting with the HTML or something. My guess is the way HTML encodes '<' and other signs('<' anyone?) . Any ideas?
No comments:
Post a Comment