forked from somujena/algo-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodified_binarysearch.txt
More file actions
55 lines (48 loc) · 1.54 KB
/
modified_binarysearch.txt
File metadata and controls
55 lines (48 loc) · 1.54 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
/* my binarysearch will return last element if target is greater than or equal to ending element and will
return -1 if target is less than starting element else it will return index which is the last element smaller
than equal to target */
///////*******************LESS THAN EQUAL TO
// end---->number of elements in vector
long int binarySearch(std::vector<long int> &arr,long int end, long int target)
{
long int start = 0;
end--;
long int ans = -1;
while (start <= end)
{
long int mid = (start + end) / 2;
if (arr[mid] > target)
{
end = mid - 1;
}
else
{
ans = mid;
start = mid + 1;
}
}
return ans;
}
/* my binarysearch will return first element if target is less than or equal to first element and will
return -1 if target is greater than ending element else it will return index which is the first element greater
than equal to target */
//////////*******************GREATER THAN EQUAL TO
// end----->number of elements in vector
long int binarySearch(std::vector<long int> &arr,long int end, long int target)
{
long int start = 0;
end--;
long int ans = -1;
while (start <= end)
{
long int mid = (start + end) / 2;
if (arr[mid] < target)
start = mid + 1;
else
{
ans = mid;
end = mid - 1;
}
}
return ans;
}