Veronica Love wrote:In studying the binary search algorithm I have noticed that a while loop is always used. However I wrote the algorithm using a for loop it works fine from what I have tested. I just wanted to know if there is any disadvantage or any other reason a for loop shouldn't be used.
I think Jeff's covered the main points: your loop looks like its saying "for each element", when what it
does is "while I haven't yet found the right index".
But the fact of the matter is that you don't actually need a loop at all.
Java allows 'recursive' methods - that is, a method can call
itself - and binary chops are a classic case where it makes a lot of sense to do so.
However, before that: have you tested your method on:
(a) an empty array.
(b) an array with exactly 1 element in it, where the value you supply is NOT it.
The fact is that you are missing a very important check. See if you can work out what it is; otherwise, come back for help.
Winston
PS: Doh-h-h!
int middle = (end - start)/2;
is also fundamentally flawed. Think about what that equation does (
write it out). However, even if you get it right (and it's
very easy to get wrong; the original code contained a problem for nearly 10 years), what I said above about your tests still applies.