-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathBinSearchAscending.java
More file actions
37 lines (28 loc) · 1 KB
/
BinSearchAscending.java
File metadata and controls
37 lines (28 loc) · 1 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
package com.company;
import java.util.Scanner;
public class BinSearchAsc {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] arr = {-34, -28, -8, -1, 4, 16, 45, 79}; //Ascending
int target = 16;
int result = binsearch(arr, target);
System.out.println(result);
}
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]){
end = middle - 1; //only the end will change if target is on the left
}
else if(target > arr[middle]){
start = middle + 1; //only the start will change if target is on the right
}
else{
return middle; //when the target is at the middle of the array
}
}
return -1;
}
}