-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
36 lines (34 loc) · 817 Bytes
/
BinarySearch.java
File metadata and controls
36 lines (34 loc) · 817 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
public class BinarySearch {
public static void main(String args[]) {
int []arr={12,30,45,90,150,200};
int item=45;
int n=arr.length;
int lowerbound = 0;
int upperbound = n - 1;
// Obtain the index of the middlemost element
int mid = (lowerbound + upperbound) / 2;
int ctr = 1; // Variable to count the number of comparisons
while ((item != arr[mid]) && (lowerbound <= upperbound)) /* Loop to search for the element in the array */
{
if (item > arr[mid])
{
lowerbound = mid + 1;
}
else
{
upperbound = mid - 1;
}
mid = (lowerbound + upperbound) / 2;
ctr++;
}
if (item == arr[mid])
{
System.out.println("\n" + item + " found at position "+(mid+1));
}
else
{
System.out.println("\n"+item+ " not found in the array\n");
}
System.out.println("\nNumber of comparisons: " + ctr);
}
}