-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathArraySearch.java
More file actions
executable file
·89 lines (62 loc) · 2.11 KB
/
ArraySearch.java
File metadata and controls
executable file
·89 lines (62 loc) · 2.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.Scanner;
public class ArraySearch {
public static void main(String args[]) {
int a[] = {5, 7, 8, -2, 3, 4, 10};
int searchElement, choice;
SearchMethod searchMethod = new SearchMethod();
System.out.println("Enter the search Element");
Scanner input = new Scanner(System.in);
searchElement = input.nextInt();
System.out.println("Select a choice:\n1.LinearSearch\n2.Binary Search");
choice = input.nextInt();
if (choice == 1)
searchMethod.linearSearch(a, a.length, searchElement);
else if (choice == 2)
searchMethod.binarySearch(a, a.length, searchElement);
else {
System.out.println("Wrong option Entered");
}
}
}
class SearchMethod {
void linearSearch(int a[], int size, int searchElement) {
int k = 5;
for (int i = 0; i < size; i++) {
if (a[i] == searchElement) {
k = 0;
}
}
if (k == 0) {
System.out.println("Yes " + searchElement + " is present in the Array");
} else {
System.out.println("Nope not here");
}
}
void binarySearch(int a[], int size, int searchElement) {
for (int i = 0; i < size; i++) {
{
for (int j = 1; j < size - i; j++) {
if (a[j - 1] > a[j]) {
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
}
int first = 0, last = size - 1, middle = (first + last) / 2;
while (first <= last) {
if (a[middle] < searchElement)
first = middle + 1;
else if (a[middle] == searchElement) {
System.out.println("Yes " + searchElement + " is present in the Array");
break;
} else
last = middle - 1;
middle = (first + last) / 2;
}
if (first > last) {
System.out.println("Nope Not here");
}
}
}