-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.java
More file actions
43 lines (35 loc) · 1.13 KB
/
Copy pathLinearSearch.java
File metadata and controls
43 lines (35 loc) · 1.13 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
// time complexity: O(n)
// space complexity: O(1)
import java.util.*;
import java.io.*;
class LinearSearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// size of an element from the user
System.out.println("Enter the number of elements present in an array");
int n = sc.nextInt();
// array elements entered from the user
System.out.println("Enter the array elements");
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
// target element from the user
System.out.println("Enter target element");
int x = sc.nextInt();
// Implementation of linear search
int idx = -1;
for(int i=0; i<n; i++){
if(arr[i] == x){
idx = i;
break;
}
}
if(idx == -1){
System.out.println("Searched element is not found in an array");
}
else{
System.out.println("Searched element is found at the location:" +idx);
}
}
}