- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckIfArrayContainsASpecificVal.java
More file actions
Latest commit
56 lines (47 loc) · 1.69 KB
/
Copy pathCheckIfArrayContainsASpecificVal.java
File metadata and controls
56 lines (47 loc) · 1.69 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
56
packageBasics;
importjava.util.Arrays;
importjava.util.Scanner;
/**
* Write a Java program to test if an array contains a specific value.
*/
publicclassCheckIfArrayContainsASpecificVal {
publicstaticvoidmain(String[] args) {
Scannerscanner = newScanner(System.in);
System.out.println("How many elements in the array ? >");
intnumOfElements = scanner.nextInt();
int[] array = newint[numOfElements];
for (inti = 0; i < array.length; i++){
System.out.println("Enter element " + (i+1));
array[i] = scanner.nextInt();
}
System.out.println("Enter the element to be found. ");
intnumToFind = scanner.nextInt();
booleanisElementPresentBinarySearch = binarySearch(array, numToFind);
booleanisElementPresentLinearSearch = linearSearch(array, numToFind);
if (!isElementPresentLinearSearch){
System.out.println("The element is not in the list");
}
}
privatestaticbooleanlinearSearch(int[] array, intnumToFind){
for (inti = 0; i < array.length; i++ ){
if (array[i] == numToFind){
System.out.println("The element is found at position " + (i+1));
returntrue;
}
}
returnfalse;
}
privatestaticbooleanbinarySearch(int[] array, intnumToFind){
Arrays.sort(array);
intmiddle = array.length / 2;
if (array[middle] < numToFind){
;
}elseif (array[middle] > numToFind){
returntrue;
}else {
System.out.println("The num is present at " + middle);
returntrue;
}
returnfalse;
}
}