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

Class BinarySearch

Programs/BinarySearch.java:3–46  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1// Java implementation of recursive Binary Search
2import java.util.*;
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[])
29 {
30 BinarySearch ob = new BinarySearch();
31 Scanner kb = new Scanner(System.in);
32 int n = kb.nextInt();
33 int arr[] = new int[n];
34 for(int i=0;i<n;i++){
35 arr[i]=kb.nextInt();
36 }
37 int length = arr.length;
38 int target = 10;
39 int result = ob.binarySearch(arr, 0, length - 1, target);
40 if (result == -1)
41 System.out.println("Element not present");
42 else
43 System.out.println("Element found at index " + result);
44 kb.close();
45 }
46}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected