Java Reference
In-Depth Information
10
return ;
11 }
12
13
double result = numbers[ 0 ];
14
15 for ( int i = 1 ; i < numbers.length; i++)
16 if (numbers[i] > result)
17 result = numbers[i];
18
19 System.out.println( "The max value is " + result);
20 }
21 }
Line 3 invokes the printMax method with a variable-length argument list passed to the array
numbers . If no arguments are passed, the length of the array is 0 (line 8).
Line 4 invokes the printMax method with an array.
6.17
What is wrong in the following method header?
public static void print(String... strings, double ... numbers)
public static void print( double ... numbers, String name)
public static double ... print( double d1, double d2)
Check
Point
6.18
Can you invoke the printMax method in Listing 6.5 using the following statements?
printMax( 1 , 2 , 2 , 1 , 4 );
printMax( new double []{ 1 , 2 , 3 });
printMax( new int []{ 1 , 2 , 3 });
6.10 Searching Arrays
If an array is sorted, binary search is more efficient than linear search for finding an
element in the array.
Key
Point
Searching is the process of looking for a specific element in an array—for example, discover-
ing whether a certain score is included in a list of scores. Searching is a common task in com-
puter programming. Many algorithms and data structures are devoted to searching. This
section discusses two commonly used approaches, linear search and binary search .
linear search
binary search
6.10.1 The Linear Search Approach
The linear search approach compares the key element key sequentially with each element in
the array. It continues to do so until the key matches an element in the array or the array is
exhausted without a match being found. If a match is made, the linear search returns the index
of the element in the array that matches the key. If no match is found, the search returns -1 .
The linearSearch method in Listing 6.6 gives the solution.
linear search animation on
Companion Website
L ISTING 6.6 LinearSearch.java
1 public class LinearSearch {
2 /** The method for finding a key in the list */
3
public static int linearSearch( int [] list, int key) {
4
for ( int i = 0 ; i < list.length; i++) {
5
if (key == list[i])
6
return i;
[0] [1] [2] …
7 }
8
list
key Compare key with list[i] for i = 0, 1, …
return - 1 ;
9 }
10 }
 
 
Search WWH ::




Custom Search