Uh oh!
There was an error while loading. Please reload this page.
forked from TheAlgorithms/Java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.java
More file actions
Latest commit
48 lines (39 loc) · 1.11 KB
/
Copy pathLinearSearch.java
File metadata and controls
48 lines (39 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
importjava.util.Scanner;
publicclassLinearSearch{
//Main method
publicstaticvoidmain(String[] args){
Scannerinput = newScanner(System.in);
int[] myArray;
intsize = 0;
//Prompt user to create array and its elements
System.out.print("Enter the array size: ");
size = input.nextInt();
myArray = newint[size];
for (inti = 0; i < size; i++){
System.out.print("For index " + i + ", enter an integer: ");
myArray[i] = input.nextInt();
}
//Prompt user to search for particular element
System.out.print("Enter integer to search for: ");
intkey = input.nextInt();
//Output array and index of target element, if found
printarray(myArray);
System.out.printf("The integer %d is found in index %d\n", key, linearsearch(myArray, key));
}
//Linear search method
publicstaticintlinearsearch(int[] list, intkey){
for (inti = 0; i< list.length; i++){
if (list[i] == key){
returni;
}
} return -1;
}
//Helper method
publicstaticvoidprintarray(int[] a){
System.out.print("The array is: ");
for( intd: a){
System.out.print(d+" ");
}
System.out.println();
}
}