Java Reference
In-Depth Information
22
// output spaces for alignment
23
for
(
int
i =
0
; i < middle; i++)
24
System.out.print(
" "
);
25
System.out.println(
" * "
);
// indicate current middle
26
27
// if the element is found at the middle
if
(key == data[middle])
location = middle;
// location is the current middle
else if
(key < data[middle])
// middle element is too high
high = middle -
1
;
// eliminate the higher half
else
// middle element is too low
low = middle +
1
;
// eliminate the lower half
28
29
30
31
32
33
34
35
middle = (low + high +
1
) /
2
;
// recalculate the middle
}
while
((low <= high) && (location ==
-1
));
36
37
38
return
location;
// return location of search key
39
}
// end method binarySearch
40
41
// method to output certain values in array
42
private static
String remainingElements(
int
[] data,
int
low,
int
high)
43
{
44
StringBuilder temporary =
new
StringBuilder();
45
46
// append spaces for alignment
47
for
(
int
i = 0; i < low; i++)
48
temporary.append(
" "
);
49
50
// append elements left in array
51
for
(
int
i = low; i <= high; i++)
52
temporary.append(data[i] +
" "
);
53
54
return
String.format(
"%s%n"
, temporary);
55
}
// end method remainingElements
56
57
public static void
main(String[] args)
58
{
59
Scanner input =
new
Scanner(System.in);
60
SecureRandom generator =
new
SecureRandom();
61
62
int
[] data =
new
int
[
15
];
// create array
63
64
for
(
int
i =
0
; i < data.length; i++)
// populate array
65
data[i] =
10
+ generator.nextInt(
90
);
66
67
Arrays.sort(data);
// binarySearch requires sorted array
Arrays.toString(data)
68
System.out.printf(
"%s%n%n",
);
// display array
69
70
// get input from user
71
System.out.print(
"Please enter an integer value (-1 to quit): "
);
72
int
searchInt = input.nextInt();
73
Fig. 19.3
|
Use binary search to locate an item in an array (the
*
in the output marks the middle
element). (Part 2 of 3.)