T
Tak
HI,EVERYONE:
That's my puzzle:
page52 of <The c programming language>(k&r),It writes:
/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-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 + 1;
else if (x > v[mid])
low = mid + 1;
else /* found match */
return mid;
}
return -1; /* no match */
}
I tested the code in my program:
#include <stdio.h>
int bserch(int x, int st[], int n);
int main()
{
int array[6] = {1,2,3,4,5,6};
int findx;
scanf("%d",&findx);
printf("%d\n",bserch(findx,array,6));
return 0;
}
int bserch(int x, int st[], int n)
{
int low,mid,high;
low = 0;
high = n-1;
while (low <= high){
mid = (low+high)/2;
if (x < st[mid])
high = mid + 1;
else if (x > st[mid])
low = mid + 1;
else
return mid + 1;
}
return -1;
}
I can't receive the correct answer when I input 1 or 4.But when I
replace the statement "high = mid + 1; " by "high = mid;" the
program run correctly. What's wrong? Do I misunderstand? Or......?
Thanks for your HELP!
That's my puzzle:
page52 of <The c programming language>(k&r),It writes:
/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-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 + 1;
else if (x > v[mid])
low = mid + 1;
else /* found match */
return mid;
}
return -1; /* no match */
}
I tested the code in my program:
#include <stdio.h>
int bserch(int x, int st[], int n);
int main()
{
int array[6] = {1,2,3,4,5,6};
int findx;
scanf("%d",&findx);
printf("%d\n",bserch(findx,array,6));
return 0;
}
int bserch(int x, int st[], int n)
{
int low,mid,high;
low = 0;
high = n-1;
while (low <= high){
mid = (low+high)/2;
if (x < st[mid])
high = mid + 1;
else if (x > st[mid])
low = mid + 1;
else
return mid + 1;
}
return -1;
}
I can't receive the correct answer when I input 1 or 4.But when I
replace the statement "high = mid + 1; " by "high = mid;" the
program run correctly. What's wrong? Do I misunderstand? Or......?
Thanks for your HELP!