-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchPractice.java
More file actions
70 lines (68 loc) · 1.9 KB
/
BinarySearchPractice.java
File metadata and controls
70 lines (68 loc) · 1.9 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
59
60
61
62
63
64
65
66
67
68
69
70
public class BinarySearchPractice {
public static void main(String[] args) {
int[] a = {1,2,7,8,11,71,88};
System.out.println(binarySearchInsertionSimple(a, 5));
}
public static int binarySearchLeftEdge(int[] nums, int target)
{
int i = binarySearchInsertion(nums, target);
if(i == nums.length || nums[i]!=target)
return -1;
return i;
}
public static int binarySearchRightEdge(int[] nums, int target)
{
/*Search the left edge of target+1, and then the index minus one is the
index of right edge of target*/
int j = binarySearchInsertion(nums, target+1)-1;
if(j == -1 || nums[j]!=target)
return -1;
return j;
}
public static int binarySearchInsertion(int[] nums, int target)
{
int i = 0, j = nums.length;
while(!(i>j))
{
int m = i + (j-i)/2;
if(nums[m]>target)
j = m-1;
if(nums[m]<target)
i = m+1;
else{
j = m-1;
}
}
return i;
}
public static int binarySearchInsertionSimple(int[] nums, int target)
{
int i = 0, j = nums.length-1;
while(!(i>j))
{
int m = j+(i-j)/2;
if(nums[m]==target)
return m;
else if(nums[m]>target)
j = m-1;
else
i = m+1;
}
return i;
}
public static int binarySearch(int[] array, int target)
{
int i = 0, j = array.length-1;
while(!(i>j))
{
int m = j+(i-j)/2;
if(array[m]==target)
return m;
else if(array[m]>target)
j = m-1;
else
i = m+1;
}
return -1;
}
}