Java Reference
In-Depth Information
1
// Fig. 19.2: LinearSearchTest.java
2
// Sequentially searching an array for an item.
3
import
java.security.SecureRandom;
4
import
java.util.Arrays;
5
import
java.util.Scanner;
6
7
public
class
LinearSearchTest
8
{
9
// perform a linear search on the data
public static int
linearSearch(
int
data[],
int
searchKey)
{
// loop through array sequentially
for
(
int
index =
0
; index < data.length; index++)
if
(data[index] == searchKey)
return
index;
// return index of integer
return
-1
;
// integer was not found
}
// end method linearSearch
10
11
12
13
14
15
16
17
18
19
20
public static void
main(String[] args)
21
{
22
Scanner input =
new
Scanner(System.in);
23
SecureRandom generator =
new
SecureRandom();
24
25
int
[] data =
new
int
[
10
];
// create array
26
27
for
(
int
i =
0
; i < data.length; i++)
// populate array
28
data[i] =
10
+ generator.nextInt(
90
);
29
30
System.out.printf(
"%s%n%n",
Arrays.toString(data)
);
// display array
31
32
// get input from user
33
System.out.print(
"Please enter an integer value (-1 to quit): "
);
34
int
searchInt = input.nextInt();
35
36
// repeatedly input an integer; -1 terminates the program
37
while
(searchInt !=
-1
)
38
{
39
int
position =
linearSearch(data, searchInt)
;
// perform search
40
41
if
(position ==
-1
)
// not found
42
System.out.printf(
"%d was not found%n%n"
, searchInt);
43
else
// found
44
System.out.printf(
"%d was found in position %d%n%n"
,
45
searchInt, position);
46
47
// get input from user
48
System.out.print(
"Please enter an integer value (-1 to quit): "
);
49
searchInt = input.nextInt();
50
}
51
}
// end main
52
}
// end class LinearSearchTest
Fig. 19.2
|
Sequentially searching an array for an item. (Part 1 of 2.)