-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_element_in_array.java
More file actions
55 lines (44 loc) · 1.51 KB
/
Copy pathsearch_element_in_array.java
File metadata and controls
55 lines (44 loc) · 1.51 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
54
55
//Check if an element exist in the array
import java.util.Scanner;
//Class that contains array and search logic
class ArraySearch{
int[] arr; //instance variable holds the value
int n; //size of an array
//Method to take input
void inputArray(Scanner sc){
System.out.println("Enter the size of an array: ");
n = sc.nextInt();
arr = new int[n]; //allocate memory
System.out.println("Enter " + n + " elements");
for(int i = 0; i<n ; i++){ //accept all the array elements
arr[i] = sc.nextInt();
}
}
boolean search(int key){
for(int i = 0 ; i<n ; i++){
if(arr[i] == key){ //check if the array element is equal to the key(the value to search)
return true;
}
}
return false;
}
}
public class search_element_in_array{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArraySearch obj = new ArraySearch(); //object of class ArraySearch
obj.inputArray(sc);
//Enter the element want to search
System.out.println("Enter the element to search: ");
int key = sc.nextInt();
if(obj.search(key)){
System.out.println("YES"); //print yes if the key exist
}
else{
System.out.println("NO"); //print no if the key do not exist
}
}
}
/*Complexity:
Time: O(n) (need to scan through the entire array in worst case)
Space: O(1) (only a few variables used)*/