-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary searches.cpp
108 lines (101 loc) · 1.86 KB
/
binary searches.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
int search(int *a, int f, int l, int n){
while(f<=l)
{
int mid=(f+l)/2;
if(a[mid]<n)
f=mid+1;
else if(a[mid]>n)
l=mid-1;
else
return mid;
}
return -1;
}
int searchLessThanEqual(int *a, int f, int l, int n){
int mid;
while(f<=l)
{
mid=(f+l)/2;
if(a[mid]<n)
f=mid+1;
else if(a[mid]>n)
l=mid-1;
else
return mid;
}
if(a[mid]>n) mid--;
return mid; //use caution of under index
}
int searchGreaterThanEqual(int *a, int f, int l, int n){
int mid;
while(f<=l)
{
mid=(f+l)/2;
if(a[mid]<n)
f=mid+1;
else if(a[mid]>n)
l=mid-1;
else
return mid;
}
if(a[mid]<n) mid++;
return mid; ///use caution of over index
}
int searchFirst(int *a, int n, int l,int h)
{
int startIndex = -1;
while (l <= h)
{
int mid = (h - l) / 2 + l;
if (a[mid] >=n)
{
h = mid - 1;
if (a[mid] == n)
startIndex = mid;
}
else
l = mid + 1;
}
return startIndex;
}
int searchCount(vi &numbers, int target)
{
int low = 0, high = numbers.sz - 1;
int startIndex = -1;
while (low <= high)
{
int mid = (high - low) / 2 + low;
if (numbers[mid] > target)
{
high = mid - 1;
}
else if (numbers[mid] == target)
{
startIndex = mid;
high = mid - 1;
}
else
low = mid + 1;
}
int endIndex = -1;
low = 0;
high = numbers.sz - 1;
while (low <= high)
{
int mid = (high - low) / 2 + low;
if (numbers[mid] > target)
{
high = mid - 1;
}
else if (numbers[mid] == target)
{
endIndex = mid;
low = mid + 1;
}
else
low = mid + 1;
}
if(endIndex!=-1 && startIndex!=-1)
return endIndex-startIndex+1;
else return 0;
}