70 lines
1.5 KiB
C
70 lines
1.5 KiB
C
#include <stdio.h>
|
|
|
|
#define SIZE 1000000
|
|
#define X 2*((SIZE-1) / 2) + 1
|
|
#define T 10000000
|
|
|
|
int binsearch(int x, int v[], int n);
|
|
int binsearch_old(int x, int v[], int n);
|
|
|
|
/* run binsearch on array of size SIZE
|
|
* if arg is provided use old binsearch */
|
|
int main(int argc, char *argv[])
|
|
{
|
|
long i;
|
|
int arr[SIZE];
|
|
|
|
for (i = 0; i < SIZE; ++i)
|
|
arr[i] = 2 * i;
|
|
|
|
if (argc == 1) {
|
|
for (i = 0; i < T; ++i)
|
|
binsearch(X, arr, SIZE);
|
|
printf("binsearch : %d\n", binsearch(X, arr, SIZE));
|
|
}
|
|
else {
|
|
for (i = 0; i < T; ++i)
|
|
binsearch_old(X, arr, SIZE);
|
|
printf("old binsearch : %d\n", binsearch_old(X, arr, SIZE));
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* binsearch: find x in sorted v of length n, using one comparison in loop */
|
|
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])
|
|
high = mid;
|
|
else
|
|
low = mid + 1;
|
|
}
|
|
if (v[low] == x)
|
|
return low;
|
|
return -1;
|
|
}
|
|
|
|
/* binsearch: find x in sorted v of length n, using two comparisons in loop */
|
|
int binsearch_old(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])
|
|
high = mid - 1;
|
|
else if (x > v[mid])
|
|
low = mid + 1;
|
|
else
|
|
return mid;
|
|
}
|
|
return -1;
|
|
}
|