-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.java
69 lines (61 loc) · 2.01 KB
/
BinarySearch.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
63
64
65
66
67
68
69
public class BinarySearch {
public int search(int[] nums, int target){
//consider array is sorted in ascending order
int right = nums.length - 1;
System.out.println("right " + right);
int left = 0;
System.out.println("left " + left);
while (left <= right ){
System.out.println("in while");
int middle = (left + right)/2;
System.out.println("middle " + middle);
if(target == nums[middle]){
return middle;
}
if(target < nums[middle] ){
right = middle-1;
System.out.println("item "+ target +" is less than "+ nums[middle]+" look in left part");
}else{
left = middle+1;
System.out.println("item "+ target +" is more than "+ nums[middle]+" look in right part");
}
}
return -1;
}
public int search2(int[] nums, int target){
//considering ascending array (1, 3 , 5 , 10)
int startIndex = 0;
int endIndex = nums.length-1;
while(startIndex <= endIndex){
int midIndex = (startIndex+endIndex)/2;
if(nums[midIndex] == target){
return midIndex;
}
if(target <= nums[midIndex])
{
endIndex = midIndex-1;
}else{
startIndex = midIndex+1;
}
}
return -1;
}
public int SearchInsertPosition(int[] nums, int target){
//considering ascending array (1, 3 , 5 , 10)
int startIndex = 0;
int endIndex = nums.length-1;
while(startIndex <= endIndex){
int midIndex = (startIndex+endIndex)/2;
if(nums[midIndex] == target){
return midIndex;
}
if(target < nums[midIndex])
{
endIndex = midIndex-1;
}else{
startIndex = midIndex+1;
}
}
return startIndex;
}
}