# Binary search problem

• 10-08-2010, 07:26 PM
billy
Binary search problem
problem solved
• 10-08-2010, 07:45 PM
KevinWorkman
Saying "it doesn't work" is pretty meaningless. How doesn't it work? What does it do differently from what you expect? Why do you think that is? Do you get any exceptions? What have you tried? What worked, and what didn't work? Why didn't it work? Be specific, and post a short piece of runnable code that demonstrates the problem.
• 10-08-2010, 07:48 PM
eRaaaa
Code:

```                System.out.print( "Enter the item to be found " );                   line = thing.readLine(); // line is a string                 search_item = Integer.valueOf(line).intValue(); // convert to int```
first:
why do you want to convert it to an integer? ;/
second:
if (search_item < a[middle]) makes no sense, because the type of a[middle] is contacts, search_item is an integer u cant compare them like you do.
you have to compare the strings! e.g. line.compareTo(a[middle].surname)

not tested and based on your code:
Code:

```                BufferedReader thing;                 thing = new BufferedReader(new InputStreamReader(System.in));                 int upper, lower, middle;                 System.out.print("Enter the item to be found ");                 String line = thing.readLine(); // line is a string                 lower = 0;                 upper = a.length - 1;                 do {                         middle = (lower + upper) / 2;                         if (line.compareTo(a[middle].surname) < 0)                                 upper = middle - 1;                         else                                 lower = middle + 1;                 } while ((!a[middle].surname.equals(line)) && (lower <= upper));                 if (a[middle].surname.equals(line))                         System.out.print("The item is at position " + middle);                 else                         System.out.print("This item is not found");```
• 10-08-2010, 08:43 PM
billy
Thank you so much.
Worked Perfect.