Created
June 22, 2011 15:01
-
-
Save ecounysis/1040276 to your computer and use it in GitHub Desktop.
Attempting to solve K&R exercise 3-1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int binsearch1(int, int[], int); | |
int binsearch2(int, int[], int); | |
int main(int argc, char *argv[]) | |
{ | |
int size = atoi(argv[2]); | |
int values[size]; | |
for(int i = 0; i < size; i++) | |
{ | |
if (i != 0) | |
values[i] = values[i-1] + (rand() % 20); | |
else | |
values[i] = 0; | |
//printf("%d\n", values[i]); | |
} | |
int x = atoi(argv[1]); | |
int v; | |
if (atoi(argv[3]) == 1) | |
v = binsearch1(x, values, size); | |
else if (atoi(argv[3]) == 2) | |
v = binsearch2(x, values, size); | |
else | |
{ | |
printf("3rd arg must be 1 or 2\n"); | |
return 0; | |
} | |
printf("%d|%d\n", x, v); | |
return 0; | |
} | |
int binsearch1(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 /* found match */ | |
return mid; | |
} | |
return -1; /* no match */ | |
} | |
int binsearch2(int x, int v[], int n) | |
{ | |
int low, high, mid; | |
if(x > v[n - 1] || x < v[0]) | |
return -1; /* it's not here */ | |
low = 0; | |
high = n -1; | |
int diff, olddiff; | |
mid = (low + high) / 2; | |
while (low <= high) | |
{ | |
diff = x - v[mid]; | |
if (diff == 0) | |
{ | |
return mid; | |
} | |
else | |
{ | |
mid += diff/2; | |
if (olddiff == diff) | |
return -1; | |
} | |
olddiff=diff; | |
} | |
return mid; /* low == high == mid */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment