-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsorted-search.cpp
More file actions
64 lines (57 loc) · 1.3 KB
/
sorted-search.cpp
File metadata and controls
64 lines (57 loc) · 1.3 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
/**
* @file sorted-search.cpp
* @author nirmeet baweja
* @brief Implement function countNumbers that accepts a sorted vector of
* unique integers and, efficiently with respect to time used, counts the
* number of vector elements that are less than the parameter lessThan.
*
* For example, for vector v containing { 1, 3, 5, 7 }, countNumbers(v, 4)
* should return 2 because there are two vector elements less than 4.
*
* @version 0.1
* @date 2022-02-12
*
* @copyright Copyright (c) 2022
*
*/
#include <vector>
#include <stdexcept>
#include <iostream>
int countNumbers(const std::vector<int> &sortedVector, int lessThan)
{
// first element is greater than lessThan, return 0
if (sortedVector[0] >= lessThan)
{
return 0;
}
// last element is smaller than lessThan, return n
int n = sortedVector.size();
if (sortedVector[n - 1] < lessThan)
{
return n;
}
int left = 0;
int right = n;
int mid = (left + right) / 2;
// use the variation of binary search algorithm
while ((mid > left) && (mid < right))
{
if (sortedVector[mid] < lessThan)
{
left = mid;
}
else
{
right = mid;
}
mid = (left + right) / 2;
}
return mid + 1;
}
#ifndef RunTests
int main()
{
std::vector<int> v{1, 3, 5, 7};
std::cout << countNumbers(v, 5) << '\n';
}
#endif