二分法查找顺序数组(C语言实现)
程序员文章站
2024-03-17 14:42:58
...
#include <stdio.h>
#include <string.h>
#define MAX_NUM 5
static int
dichotomy_check_the_number(int *array, int value, int size)
{
int min, mid, max, ret;
ret = -1;
min = 0;
max = size;
while(min <= max){
//mid = (min + max)/2;
mid = min+(value-array[min])*(max-min)/(array[max]+array[min]);
if( array[mid] == value ){
ret = mid;
break;
}
else{
if( array[mid] < value)
min = mid + 1;
else
max = mid - 1;
}
}
return ret;
}
int
main(int argc, char **argv)
{
int array[MAX_NUM];
int i, value, tmp, ret;
memset(array, 0, MAX_NUM);
printf("input the array of int:\n");
for(i = 0; i < MAX_NUM; i++){
scanf("%d", &tmp);
array[i] = tmp;
}
printf("input the check value:\n");
scanf("%d", &tmp);
value = tmp;
ret = dichotomy_check_the_number(array, tmp, MAX_NUM);
if(ret != -1){
printf("the ret is %d, the value is %d\n", ret, array[ret]);
}else{
printf("not find\n");
}
return 0;
}
结果:
下一篇: PAT A1010 Radix题解