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
|
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
bool binarySearch(int a[], int size, int k);
int main()
{
int a[] = {1,2,3,4,5};
assert(binarySearch(a,5,5)== true);
int b[] = {-9,-4,0,2,4,12,99};
assert(binarySearch(b,7,5)== false);
int c[] = {0,10,12,14,20};
assert(binarySearch(c,5,5)== false);
int d[] = {-1000,10,99,100,1000};
assert(binarySearch(d,5,99)== true);
cout << "All tests have successfully passed." << endl;
}
bool binarySearch(int a[], int size, int k)
{
int s = 0; // 's' stands for the starting point of the binary search algorithm.
int e = size - 1; // 'e' stands for the ending point of the binary search algorithm.
while(s <=e)
{
int m = (s + e)/2; // 'm' stands for the midpoint of the binary search algorithm.
if(k == a[m])
{
return true;
}
else if(k < a[m])
{
e = m - 1;
}
else
{
s = m + 1;
}
}
return false;
}
|