19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

6.10 Searching Arrays 247<br />

key is 11<br />

low<br />

mid<br />

high<br />

key 50<br />

key 7<br />

key 11<br />

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]<br />

list 2 4 7 10 11 45 50 59 60 66 69 70 79<br />

low mid high<br />

[0] [1] [2] [3] [4] [5]<br />

list 2 4 7 10 11 45<br />

low mid high<br />

[3] [4] [5]<br />

list 10 11 45<br />

FIGURE 6.10<br />

<strong>com</strong>parison.<br />

Binary search eliminates half of the list from further consideration after each<br />

public static int binarySearch(<br />

int[] list, int key) {<br />

int low = 0;<br />

int high = list.length - 1;<br />

int mid = (low + high) / 2;<br />

if (key < list[mid])<br />

high = mid - 1;<br />

else if (key == list[mid])<br />

return mid;<br />

else<br />

low = mid + 1;<br />

public static int binarySearch(<br />

int[] list, int key) {<br />

int low = 0;<br />

int high = list.length - 1;<br />

while (high >= low) {<br />

int mid = (low + high) / 2;<br />

if (key < list[mid])<br />

high = mid - 1;<br />

else if (key == list[mid])<br />

return mid;<br />

else<br />

low = mid + 1;<br />

}<br />

}<br />

}<br />

return -1;<br />

// Not found<br />

(a) Version 1<br />

(b) Version 2<br />

FIGURE 6.11 Binary search is implemented incrementally.<br />

indicate that the key matches list[0]. A good choice is <strong>to</strong> let the method return –low – 1<br />

if the key is not in the list. Returning –low – 1 indicates not only that the key is not in the list,<br />

but also where the key would be inserted.<br />

The <strong>com</strong>plete program is given in Listing 6.7.<br />

LISTING 6.7<br />

BinarySearch.java<br />

1 public class BinarySearch {<br />

2 /** Use binary search <strong>to</strong> find the key in the list */<br />

3 public static int binarySearch(int[] list, int key) {<br />

4 int low = 0;<br />

5 int high = list.length - 1;<br />

6<br />

7<br />

8<br />

while (high >= low) {<br />

int mid = (low + high) / 2;<br />

9 if (key < list[mid])<br />

10 high = mid - 1;<br />

11 else if (key == list[mid])<br />

first half

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!