-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchAscendingDescending.java
63 lines (51 loc) · 1.48 KB
/
BinarySearchAscendingDescending.java
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
59
60
61
62
package Arrays;
public class BinarySearchAscendingDescending {
public static void main (String[]args) {
int arr1[]={23,56,76,83,118}; //ascending
int arr2[]={110,89,68,54,12}; // descending
searchAscending(arr1,83);
searchDescending(arr2,89);
}
public static void searchAscending(int arr[],int toS) {
int ub=arr.length-1,lb=0,mb;
int fn=-1; // found index
while(lb<=ub){
mb=(ub+lb)/2;
if (arr[mb]==toS){
fn=mb;
break;
}
else if (toS>arr[mb]){
lb=mb+1;
}
else{
ub=mb-1;
}
}
if (fn!=-1)
System.out.println("Number of found at : "+fn+" index");
else
System.out.println("Number not found");
}
public static void searchDescending(int arr[],int toS) {
int ub=arr.length-1,lb=0,mb;
int fn=-1; // found index
while(lb<=ub){
mb=(ub+lb)/2;
if (arr[mb]==toS){
fn=mb;
break;
}
else if (arr[mb]>toS){
lb=mb+1;
}
else{
ub=mb-1;
}
}
if (fn!=-1)
System.out.println("Number of found at : "+fn+" index");
else
System.out.println("Number not found");
}
}