-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
44 lines (37 loc) · 797 Bytes
/
Copy pathBinarySearch.java
File metadata and controls
44 lines (37 loc) · 797 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
39
40
41
42
43
44
package leon.algorithm.search;
import java.util.Arrays;
import java.util.Random;
public class BinarySearch {
public static void main(String str[]){
Random rd = new Random();
int[] a = new int[20];
for(int i=0;i<a.length;i++){
a[i]=rd.nextInt(100);
System.out.print(a[i]+" ");
}
System.out.println();
Arrays.sort(a);
for(int i: a){
System.out.print(i+" ");
}
System.out.println();
System.out.println(binarySearch(70, a));
}
public static int binarySearch(int target, int[] a){
int result = -1;
int left = 0;
int right = a.length-1;
while(left <= right){
int mid = (left+right)>>1;
if(a[mid]==target){
result = mid;
break;
} else if (a[mid]<target){
left = mid+1;
}else{
right = mid-1;
}
}
return result;
}
}