-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
43 lines (30 loc) · 993 Bytes
/
BinarySearch.java
File metadata and controls
43 lines (30 loc) · 993 Bytes
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
public class BinarySearch {
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in);
int[] even = {2, 4, 6, 8, 10, 12};
System.out.println("Enter the value you want to search in the array : ");
int key = sc.nextInt();
int result = search(even, key);
System.out.println("The index of " +key+ " is : "+result);
sc.close();
}
private static int search(int[] array, int key)
{
int start = 0;
int end = array.length-1;
// int mid = (start + end)/2;
int mid = start + (end - start)/2;
while(start <= end)
{
if(array[mid] == key)
return mid;
if(key > array[mid])
start = mid + 1;
else if(key < array[mid])
end = mid - 1;
mid = start + (end - start)/2;
}
return -1;
}
}