MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / BinarySearch

Class BinarySearch

Java/Array/BinarySearch.java:46–89  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

44import java.util.Scanner;
45
46public class BinarySearch {
47
48 public static int binarySearch(int [] arr, int x) {
49 int n = arr.length;
50 int start = 0;
51 int end = n - 1;
52
53 while ( start <= end) {
54 int mid = (start + end)/2;
55
56 if ( arr[mid] > x) {
57 end = mid - 1;
58 } else if (arr[mid] < x) {
59 start = mid + 1;
60 } else if ( arr[mid] == x) {
61 return mid;
62 }
63 }
64 return -1;
65 }
66
67
68 public static int [] takingInput() {
69 Scanner sc = new Scanner(System.in);
70 System.out.println("Enter the length of the Array: ");
71 int n = sc.nextInt();
72 int [] arr = new int[n];
73
74 System.out.println("Enter the elements of the array:" );
75 for (int i = 0; i < n; i++) {
76 arr[i] = sc.nextInt();
77 }
78 return arr;
79 }
80
81 public static void main(String[] args) {
82 int [] arr = takingInput();
83 System.out.println("Enter the required number: ");
84 Scanner sc = new Scanner(System.in);
85 int a = sc.nextInt();
86 int n = binarySearch(arr, a);
87 System.out.println("Index of the required number is: " +n);
88 }
89}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected