I am having problems with my timing functions here. I have a program that is timing how long a binary search is taking to find a given number in a list of sorted elements in an array.
So i am getting strange results and I'm not sure why.
For example this last run i did, the program said that it took 0 microseconds to find the value not in the array of size 100,000 elements, but just before it the program searched an array of 95,000 elements which also found the value was not in the array yet it took 4080005 microseconds.
Here is my function code. Thanks for any help!
int binarySearch(int array[], int numElems, int value)
{
auto start =chrono::steady_clock::now();
cout << "Searching..."<< endl;
//variables
int first = 0,
last = numElems - 1,
middle,
position = -1;
bool found = false;
//Checks values for match
while (!found && first <= last)
{
//divides elements
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
auto end = chrono::steady_clock::now();
auto elasped = std::chrono::duration_cast<std::chrono::microseconds>(end-start);
cout << "Time Taken: " << elasped.count() << " microseconds." << endl;
return position;
}