MCPcopy Create free account
hub / github.com/Rishabh062/Hacktoberfest2021 / binarySearch

Method binarySearch

Java/BinarySearch.java:12–30  ·  view source on GitHub ↗
(int[] arr, int target)

Source from the content-addressed store, hash-verified

10 // return the index
11 // return -1 if it does not exist
12 static int binarySearch(int[] arr, int target) {
13 int start = 0;
14 int end = arr.length - 1;
15 while(start <= end) {
16 // find the middle element
17// int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java
18 int mid = start + (end - start) / 2;
19
20 if (target < arr[mid]) {
21 end = mid - 1;
22 } else if (target > arr[mid]) {
23 start = mid + 1;
24 } else {
25 // ans found
26 return mid;
27 }
28 }
29 return -1;
30 }
31}

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected