-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathBinarySearch.java
46 lines (41 loc) · 1.24 KB
/
BinarySearch.java
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
// Java implementation of recursive Binary Search
import java.util.*;
class BinarySearch {
// Returns index of target if it is present in arr else return -1
int binarySearch(int arr[], int first, int last, int target)
{
if (last >= first) {
int mid = first + (last - first) / 2;
// if element is present in the middle
if (arr[mid] == target)
return mid;
// If element is smaller than mid, then it can only be present in first subarray
if (target < arr[mid])
return binarySearch(arr, first, mid - 1, target);
// Else the element can only be present in the second subarray
return binarySearch(arr, mid + 1, last, target);
}
// We reach here when element is not present
// in array
return -1;
}
// Driver method to test above
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i]=kb.nextInt();
}
int length = arr.length;
int target = 10;
int result = ob.binarySearch(arr, 0, length - 1, target);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result);
kb.close();
}
}