7/21/2019 15-binary-search.ppt
http://slidepdf.com/reader/full/15-binary-searchppt 1/5
Building Java Programs
Chapter 13
Searching
reading: 13.3
7/21/2019 15-binary-search.ppt
http://slidepdf.com/reader/full/15-binary-searchppt 2/5
2
Binary search (13.1)
binary search: ocates a target value in a sortedarray!list "y successively eliminating hal# o# the array #romconsideration.
$o% many elements %ill it need to e&amine' O(log N)
Can "e implemented %ith a loop or recursively
&le: Searching the array "elo% #or the value 42:
inde
x
0 1 2 3 4 5 6 7 8 9 1
0
1
1
1
2
1
3
1
4
1
5
16
value
-4 2 7 10
15
20
22
25
30
36
42
50
56
68
85
92
103
min
mid ma
x
7/21/2019 15-binary-search.ppt
http://slidepdf.com/reader/full/15-binary-searchppt 3/5
3
Binary search code
// Returns the index of an occurrence of target in a,// or a negative number if the target is not found.// Precondition: elements of a are in sorted orderpublic static int binarySearch(int[] a, int target) {
int min = 0;
int max = a.length - 1;
hile (min != max) {
int mi" = (min # max) $ %;
i& (a[mi"] ! target) {
min = mi" # 1;
' else i& (a[mi"] target) {
max = mi" - 1;
' else { return mi"; // target found '
'
return -(min # 1); // target not found
'
7/21/2019 15-binary-search.ppt
http://slidepdf.com/reader/full/15-binary-searchppt 4/5
*ecursive "inary search (13.3)
+rite a recursive binarySearch method.,# the target value is not #ound- return its negative insertion
point.
int in"ex = binarySearch("ata, %); // 10
int in"ex% = binarySearch("ata, **); // -14
inde
x
0 1 2 3 4 5 6 7 8 9 1
0
1
1
1
2
1
3
1
4
1
5
16
valu
e
-4 2 7 1
0
1
5
2
0
2
2
2
5
3
0
3
6
4
2
5
0
5
6
6
8
8
5
9
2
10
3
7/21/2019 15-binary-search.ppt
http://slidepdf.com/reader/full/15-binary-searchppt 5/5
&ercise solution
// Returns the index of an occurrence of the given value in// the given array, or a negative number if not found.// Precondition: elements of a are in sorted orderpublic static int binarySearch(int[] a, int target) { return binarySearch(a, target, 0, a.length - 1);'
// Recursive heler to imlement search behavior. rivate static int binarySearch(int[] a, int target, int min, int max) { i& (min max) { return -1; // target not found ' else { int mi" = (min # max) $ %; i& (a[mi"] ! target) { // too small! go right
return binary"earch#a, target, mid $ 1, max%; ' else i& (a[mi"] target) { // too large! go left return binary"earch#a, target, min, mid - 1%; ' else { return mi"; // target found! a&mid' (( target ' '
'