Our binary search makes two tests inside the loop, when one would suffice (at the price of more tests outside). Write a version with only one test inside the loop and measure the difference in run-time.
Function before:
Code:int binsearch(int x, int v[], int n) {
int low, mid, high;
low = 0;
high = n - 1;
while ( low <= high ) {
mid = (low+high) / 2;
if ( x < v[mid] )
high = mid - 1;
else if ( x > v[mid] )
low = mid + 1;
else
return mid;
}
return -1;
}
Function after:
Code:int binsearch(int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n - 1;
while(low<=high)
{
mid = (low+high)/2;
if(x > v[mid])
low = mid + 1;
else high = mid - 1;
}
return (x == v[mid]) ? mid : -1;
}
What does measuring run time means and how am i supposed to measure it?
K&R didnt cover any clock() functions up to this point, so is there any alternative?