# Binary search infinite loop

Page 1 of 1

## 1 Replies - 218 Views - Last Post: 19 July 2012 - 12:06 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=286325&amp;s=893026d21598d91f50f5f2eba75f8994&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 dman187

• New D.I.C Head

Reputation: 0
• Posts: 6
• Joined: 02-July 12

# Binary search infinite loop

Posted 19 July 2012 - 11:47 AM

i keep getting an infinite loop when i try this binary search. can you help me to see where my logic is wrong?
```public static int binarySearch( String[] input, String searchFor ) {
if(null == input)
return -1;

int low =0;
int high = input.length;
int middle = (high+low)/2;

while(high >low){
if(input[middle].equals(searchFor)){
return middle;}
if (input[middle].compareTo(searchFor)>0){
high = middle;
}
else {

low = middle;
}
middle = (high+low)/2;

}

return -1;
}	// end binarySearch

```

Is This A Good Question/Topic? 0

## Replies To: Binary search infinite loop

### #2 SwiftStriker00

• Microsoft Insider

Reputation: 429
• Posts: 1,596
• Joined: 25-December 08

## Re: Binary search infinite loop

Posted 19 July 2012 - 12:06 PM

In your algorithm you don't want to set low=middle, because, that will get it stuck when you search for something that doesnt exist. You want to search 1 away from the middle

```if (input[middle].compareTo(searchFor)>0)
{
high = middle-1;
}
else
{
low = middle + 1;
}

```