• Post Reply Bookmark Topic Watch Topic
  • New Topic

Binary Search problem  RSS feed

 
tom davies
Ranch Hand
Posts: 168
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to make a binary search for my array. Sometimes it works fine, other times it prints out the error message, and the different variables i use in my calculation.
I have found that when the error occurs, mid is always one behind the value found at that point in the array.

An example error output:
error
number to find :> 4678 Mid :> 4677 ArrayMid :> 4678 lowerBound :> 4673 upperBound :> 4681

and the search algorithm:
 
Suresh Sajja
Ranch Hand
Posts: 34
Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
tom davies wrote:


Shouldn't this comparison be " if(sortedArray[mid] == numberToFind) " ?
 
Suresh Sajja
Ranch Hand
Posts: 34
Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Going beyond your post:

There is a bug in this line

int mid = (lowerBound + upperBound)/2;

It should be

int mid = lowerBound + ((upperBound- lowerBound ) / 2);

Please read more from Google research blog



 
tom davies
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, that seems to be working for me now. Also an interesting article.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!