forked from nishitpanchal395/projecthactoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.java
More file actions
58 lines (51 loc) · 1.65 KB
/
binarySearch.java
File metadata and controls
58 lines (51 loc) · 1.65 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
//TO Search a number from a given shorted array using the binary search
import java.util.Scanner;
public class binarySearch {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int ans = bin(arr, num);
if (ans == -1) {
System.out.println("Number not matched");
} else
System.out.println(num + " is at the index " + ans);
sc.close();
}
static int bin(int[] arr, int target) {
int st = 0;
int end = arr.length - 1;
// for the dessending shorted array
if (arr[st] > arr[end]) {
while (st <= end) {
int mid = st + (end - st) / 2;
// if (arr[st] > arr[end]) {
if (target < arr[mid]) {
st = mid + 1;
} else if (target > arr[mid]) {
end = mid - 1;
} else {
// number found (target==arr[mid])
return mid;
}
}
}
// for the assending shorted array
if (arr[st] < arr[end]) {
while (st <= end) {
int mid = st + (end - st) / 2;
// if (arr[st] > arr[end]) {
if (target < arr[mid]) {
end = mid - 1;
} else if (target > arr[mid]) {
st = mid + 1;
} else {
// number found (target==arr[mid])
return mid;
}
}
}
// number not found!!
return -1;
}
}