From 7e0f021a9aec35fd8e6725e87e3313b101d26f5e Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Sun, 27 Jan 2008 11:37:44 +0100 Subject: Initial import (2.0.2-6) --- reference/C/CONTRIB/OR_PRACTICAL_C/14_08.c | 77 ++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 reference/C/CONTRIB/OR_PRACTICAL_C/14_08.c (limited to 'reference/C/CONTRIB/OR_PRACTICAL_C/14_08.c') diff --git a/reference/C/CONTRIB/OR_PRACTICAL_C/14_08.c b/reference/C/CONTRIB/OR_PRACTICAL_C/14_08.c new file mode 100644 index 0000000..917c702 --- /dev/null +++ b/reference/C/CONTRIB/OR_PRACTICAL_C/14_08.c @@ -0,0 +1,77 @@ +/******************************************************** + * search -- Search a set of numbers. * + * * + * Usage: * + * search * + * you will be asked numbers to lookup * + * * + * Files: * + * numbers.dat -- numbers 1 per line to search * + * (Numbers must be ordered) * + ********************************************************/ +#include +#define MAX_NUMBERS 1000 /* Max numbers in file */ +#define DATA_FILE "numbers.dat" /* File with numbers */ + +int data[MAX_NUMBERS]; /* Array of numbers to search */ +int max_count; /* Number of valid elements in data */ +main() +{ + FILE *in_file; /* Input file */ + int middle; /* Middle of our search range */ + int low, high; /* Upper/lower bound */ + int search; /* number to search for */ + char line[80]; /* Input line */ + + in_file = fopen(DATA_FILE, "r"); + if (in_file == NULL) { + (void)fprintf(stderr,"Error:Unable to open %s\n", DATA_FILE); + exit (8); + } + + /* + * Read in data + */ + + max_count = 0; + while (1) { + if (fgets(line, sizeof(line), in_file) == NULL) + break; + + /* convert number */ + (void)sscanf(line, "%d", &data[max_count]); + max_count++; + } + + while (1) { + (void)printf("Enter number to search for or -1 to quit:" ); + (void)fgets(line, sizeof(line), stdin); + (void)sscanf(line, "%d", &search); + + if (search == -1) + break; + + low = 0; + high = max_count; + + while (1) { + if (low >= high) { + (void)printf("Not found\n"); + break; + } + + middle = (low + high) / 2; + + if (data[middle] == search) { + (void)printf("Found at index %d\n", middle); + break; + } + + if (data[middle] < search) + low = middle +1; + else + high = middle -1; + } + } + return (0); +} -- cgit v1.2.3-54-g00ecf