This program does binary search and linear search (many times so they can be easily timed). On the OP's condition that the search value is usually not found, the linear search takes approximately twice as long as the binary search. It takes 3 iterations of the binary search to reduce 8 elements to 1, but 8 iterations of the linear search. I used unsigned int
rather than unsigned long
.
#include <stdio.h>
#include <time.h>
#define ARRLEN 8
#define LOOPS 0x7FFFFF
unsigned user_values[ARRLEN] = { 1, 234, 8124, 8335, 10234, 11285, 637774, 788277 };
int main (int argc, char *argv[]) {
unsigned val;
int bot, top, mid, loop;
clock_t start, elap;
if (argc < 2) return 1;
if (sscanf (argv[1], "%u", &val) != 1) return 1;
// binary search
printf ("Binary search for %u: ", val);
start = clock();
for (loop=0; loop!=LOOPS; loop++) {
bot = 0;
top = ARRLEN;
while (top-bot > 1) {
mid = ((top + bot) >> 1);
if (user_values[mid] <= val)
bot = mid;
else top = mid;
}
}
elap = clock() - start;
if (user_values[bot] == val)
printf ("found");
else printf ("not found");
printf (" in count %u\n", (unsigned)elap);
// linear search
printf ("Linear search for %u: ", val);
start = clock();
for (loop=0; loop!=LOOPS; loop++) {
for (bot=0; bot<ARRLEN; bot ++)
if (user_values[bot] == val)
break;
}
elap = clock() - start;
if (bot<ARRLEN)
printf ("found");
else printf ("not found");
printf (" in count %u\n", (unsigned)elap);
return 0;
}