欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分法查找顺序数组(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;
}

结果:

二分法查找顺序数组(C语言实现)