-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.java
More file actions
53 lines (42 loc) · 1.29 KB
/
LinearSearch.java
File metadata and controls
53 lines (42 loc) · 1.29 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
49
50
51
52
53
import java.util.Scanner;
public class LinearSearch {
public static void main(String[] args) {
//Create the scanner object
Scanner scanner = new Scanner(System.in);
//prompt the user for an array of values
System.out.println("Enter array of values ");
//intialize the array
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
//prompt the user for the target value
System.out.println("\nEnter value to search for: ");
//set target value
int target = scanner.nextInt();
//perform linear search
int position = linearSearch(arr, target);
if (position != -1){
System.out.println("\nElement found at position : " +position);
} else {
System.out.println("Element not found");
}
// Close the scanner
scanner.close();
}
/*
* the linear search method takes 2 parameters
* one is the array(the Data structure) we are searching through
* two is the targer (the actual value we are searching for)
*/
static int linearSearch(int[] arr , int target){
//for loop to loop through the array elements one by one
for (int i=0; i < arr.length; i++){
//compare the current element with the target value
if (arr[i] == target){
return i;
}
}
return -1 ;//if target is not found
}
}