#include
#include
#define COMPARE(x, y) ((x) < (y) ? -1 : ((x)>(y) ? 1:0))
int compare(int x, int y)
{
if(x
else if(x>y) return 1;
else return 0;
}
//---
int binmiddle(int list[], int search, int left, int right)
{
int mid=0;
while(left <= right)
{
mid = (left+right)/2;
switch (COMPARE(list[mid], search)) {
case -1: left = mid+1; break;
case 0: return mid;
case 1: right = mid-1;
}
}
return -1;
}
//---递归实现
int binmiddle(int list[], int search, int left, int right)
{
int mid=0;
if (left <= right)
{
mid = (left+right)/2;
switch (COMPARE(list[mid], search)) {
case -1: return binmiddle(list, search, mid+1, right);
case 0: return mid;
case 1: return binmiddle(list, search, left, mid-1);
}
}
return -1;
}
//---
int main(void)
{
int r = 0;
int list[8] = {4,6,7,9,10,12,18,34};
r = binmiddle(list, 9, 0, 7);
printf("r is %d \n", r); //r is 5
return 0;
}
/*-- E --*/
谢谢欣赏,欢迎指正!
阅读(680) | 评论(0) | 转发(0) |