-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathBinSearchDescending.java
More file actions
38 lines (28 loc) · 824 Bytes
/
BinSearchDescending.java
File metadata and controls
38 lines (28 loc) · 824 Bytes
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
//code for binary searching a target element in Descending sorted array
package com.company;
import java.util.Scanner;
public class BinSearchDesc {
public static void main(String[] args) {
int[] arr = {6, 5, 4, 3, 2, 1};
int target = 2;
int res = binsearch(arr, target);
System.out.println(res);
}
private static int binsearch(int[] arr, int target) {
int start = 0;
int end = arr.length-1;
while(start <= end){
int middle = start + (end - start) / 2;
if(target < arr[middle]){
start = middle + 1;
}
else if(target > arr[middle]){
end = middle - 1;
}
else{
return middle;
}
}
return start;
}
}