-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Search Algorithm (Iterative Method).java
More file actions
39 lines (33 loc) · 1.15 KB
/
Binary Search Algorithm (Iterative Method).java
File metadata and controls
39 lines (33 loc) · 1.15 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
/* BINARY SEARCH ALGORITHM (ONLY FOR SORTED ARRAY)
Binary Search is a searching algorithm used in a sorted array by repeatedly
dividing the search interval in half.
The idea of binary search is to use the information that the array is sorted
and reduce the time complexity to O(Log n).
*/
class Main{
public static int binary_search(int arr[],int low,int high,int x)
{
while(low<=high) // repeat search until low=high
{
int mid = (low+high)/2;
if(x==arr[mid])
return mid;
else if(x>arr[mid])
low = mid+1; // new low for divided array
else
high = mid-1; // new high for divided array
}
return -1; // if element not found
}
public static void main(String[] args)
{
int arr[] = {12,34,45,67,89,112,119};
int x = 34;
int last = arr.length-1; // last index
int n = binary_search(arr,0,last,x);
if(n==-1)
System.out.println("Element not found");
else
System.out.println("Element found at index: "+n);
}
}