-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
58 lines (43 loc) · 1.34 KB
/
BinarySearch.java
File metadata and controls
58 lines (43 loc) · 1.34 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
54
55
56
57
58
package com.mycompany.algorithm_final_project;
import java.util.Scanner;
/**
*
* @author israkkayumchowdhury
*/
public class BinarySearch {
public static int binary_search(int[] arr, int target){
int left = 0;
int right = arr.length - 1;
while(left <= right){
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
}
else{
right = mid - 1;
}
}
return -1;
}
public void main_func(){
Scanner s = new Scanner(System.in);
System.out.print(" Enter the number of elements: ");
int n = s.nextInt();
int[] arr = new int[n];
System.out.print(" Enter the elements: ");
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
System.out.print(" Enter the target element to search: ");
int target = s.nextInt();
int index = binary_search(arr, target);
if (index != -1) {
System.out.println(" Element " + target + " found at index " + index);
} else {
System.out.println(" Element " + target + " not found in the array!");
}
}
}