Implement a function that uses binary search to find a given
Implement a function that uses binary search to find a given value k in an array of integers a whose elements are in increasing order. If the value is found, the function returns the index of the value in the array; otherwise it returns -1. For example, for a = (-2, 4, 5, 6, 8) and k = 1, the function returns -1. For k = 5 it returns 2. A declaration of the function is given above. Write your own implementation of binary search; do not use the search function available in the C++ standard library.
Write test code that thoroughly tests your function. Express your tests using assertions.
Solution
Binary.cpp
#include <iostream>
#include <cassert>
using namespace std;
int binarySearch(int a[], int size, int k);
int main()
{
int a[]= {2, 4, 5, 6, 8};
assert (binarySearch(a,5,1) == -1);
assert (binarySearch(a,5,6) == 3);
assert (binarySearch(a,5,4) == 1);
return 0;
}
int binarySearch(int a[], int size, int k)
{
int start = 0;
int end = size - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (k == a[mid]) {
return mid;
}
if (k < a[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
