#include <stdio.h>
#define ORIGINAL 0
#define SOLUTION 1
int binsearch(int x, int v[], int n);
int main(void){
int i, n;
unsigned int x = 0xFF30;
int v[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
/*for(i = 0; i <= 9; i++)
printf("%d%4d\n", i, binsearch(i, v, 10));*/
printf("%d%4d\n", 0, binsearch
(0, v
, 10)); printf("%d%4d\n", 9, binsearch
(9, v
, 10)); printf("%d%4d\n", 3, binsearch
(3, v
, 10)); printf("%d%4d\n", 60, binsearch
(60, v
, 10)); printf("%d%4d\n", -2, binsearch
(-2, v
, 10));
return 0;
}
#if ORIGINAL
/*Èñõîäíûé âàðèàíò áèíàðíîãî ïîèñêà*/
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 - 1;
else if(x > v[mid])
low = mid + 1;
else
return mid;
}
return - 1;
}
#endif
#if SOLUTION
/*Ðåøåíèå çàäà÷è 3.1*/
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;
printf("low = %d, high = %d\n", low
, high
); }
if(v[high] == x && v[low] == x)
return high;
else
return -1;
}
#endif
I2luY2x1ZGUgPHN0ZGlvLmg+CgojZGVmaW5lIE9SSUdJTkFMIDAKI2RlZmluZSBTT0xVVElPTiAxCgppbnQgYmluc2VhcmNoKGludCB4LCBpbnQgdltdLCBpbnQgbik7CgoKaW50IG1haW4odm9pZCl7CglpbnQgaSwgbjsKCXVuc2lnbmVkIGludCB4ID0gMHhGRjMwOwoJaW50IHZbXSA9IHswLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5fTsKCQoJLypmb3IoaSA9IDA7IGkgPD0gOTsgaSsrKQoJCXByaW50ZigiJWQlNGRcbiIsIGksIGJpbnNlYXJjaChpLCB2LCAxMCkpOyovCglwcmludGYoIiVkJTRkXG4iLCAwL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