# Binary Search method

Page 1 of 1

## 4 Replies - 518 Views - Last Post: 15 May 2014 - 04:18 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=346957&amp;s=4afd817a314c9c5800d47993d9ab003b&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 smalld01

Reputation: 1
• Posts: 70
• Joined: 25-February 14

# Binary Search method

Posted 14 May 2014 - 06:47 PM

We are required to write a binary‐search method to find an int within an array of ints. Without using any functions besides the basics (for loops, if statements, etc.)

I have this so far:

```public int binarySearch(int[] ints, int n) {
for(int i = 0; i < ints.length; i++) {
if(ints[i] == n) {
return ints[i];
}
}
}

```

Does this look somewhat correct?

Is This A Good Question/Topic? 0

## Replies To: Binary Search method

### #2 jon.kiparsky

• Pancakes!

Reputation: 9535
• Posts: 16,482
• Joined: 19-March 11

## Re: Binary Search method

Posted 14 May 2014 - 09:08 PM

No, that's a linear search. A binary search reduces the search space by fifty percent on each iteration, so the time it takes is proportional to log(n) in the worst case. A linear search reduces the search space by one on each iteration, and so it takes time proportional to n.

I'm starting to think you should spend more time with your books and less time posting every half-assed stab at an answer that you come up with.

### #3 smalld01

Reputation: 1
• Posts: 70
• Joined: 25-February 14

## Re: Binary Search method

Posted 15 May 2014 - 03:02 PM

So how would I rearrange my if statement to get started on sorting it the way you explained?

### #4 astonecipher

Reputation: 1725
• Posts: 7,088
• Joined: 03-December 12

## Re: Binary Search method

Posted 15 May 2014 - 03:22 PM

A binary search splits the array in half. The first decision it makes is, does it need to search the lower haf of the array or the upper half.

In order to do that it either is passed a sorted array or sorts it within the method.

### #5 smalld01

Reputation: 1
• Posts: 70
• Joined: 25-February 14

## Re: Binary Search method

Posted 15 May 2014 - 04:18 PM

This is what I came up with (after going through selectionSort in ascending order):

```public int binarySearch(int[] ints, int n) {
selectionSort(ints);
int low = 0;
int high = ints.length - 1;
int mid = (low + high) / 2;
while(low <= high && (ints[mid] != n)){
if(ints[mid] < n) {
low = mid + 1;
} else {
high = mid - 1;
}
mid = (low + high) /2;
}
if(low > high) {
mid = -1; //returns -1 if n is not in the array of ints
}
return mid;
}

```