MCPcopy Create free account
hub / github.com/PrajaktaSathe/Java / binarySearch

Method binarySearch

Programs/BinarySearch.java:5–25  ·  view source on GitHub ↗
(int arr[], int first, int last, int target)

Source from the content-addressed store, hash-verified

3class BinarySearch {
4 // Returns index of target if it is present in arr else return -1
5 int binarySearch(int arr[], int first, int last, int target)
6 {
7 if (last >= first) {
8 int mid = first + (last - first) / 2;
9
10 // if element is present in the middle
11 if (arr[mid] == target)
12 return mid;
13
14 // If element is smaller than mid, then it can only be present in first subarray
15 if (target < arr[mid])
16 return binarySearch(arr, first, mid - 1, target);
17
18 // Else the element can only be present in the second subarray
19 return binarySearch(arr, mid + 1, last, target);
20 }
21
22 // We reach here when element is not present
23 // in array
24 return -1;
25 }
26
27 // Driver method to test above
28 public static void main(String args[])

Callers 2

mainMethod · 0.95
exponentialSearchMethod · 0.80

Calls

no outgoing calls

Tested by

no test coverage detected