-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
53 lines (45 loc) · 1.47 KB
/
Copy pathBinarySearch.java
File metadata and controls
53 lines (45 loc) · 1.47 KB
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
47
48
49
50
51
52
53
// time complexity: O(logN)
// space complexity: O(1)
import java.util.*;
import java.io.*;
public class BinarySearch {
public static int binarySearch(int[] arr, int target){
int low=0, high = arr.length - 1;
while(low <= high){
int mid = low + (high - low)/2;
if(arr[mid] == target){
return mid;
}
else if(arr[mid] < target){
low = mid + 1;
}
else{
high = mid - 1;
}
}
return 0;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// size of an element from the user
System.out.println("Enter the number of elements present in an array");
int n = sc.nextInt();
// array elements entered from the user
System.out.println("Enter the array elements");
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
// target element from the user
System.out.println("Enter target element");
int x = sc.nextInt();
// Function calling of binarySearch
int result = binarySearch(arr, x);
if(result == 0){
System.out.println("Searched element is not found in an array");
}
else{
System.out.println("Searched element is found at the location:" +result);
}
}
}