0
点赞
收藏
分享

微信扫一扫

C语言之二分法

卿卿如梦 2022-04-05 阅读 59

C语言之二分法

从键盘输入一个数,判断该数属不属于这些数(12,0,6,16,23,56,80,100,110,115),若属于,同时输出是第几个数。

代码示例:
[liangjian@localhost ~]$ cat test3.c 
#include <stdio.h>
#define M 10
 
void main()
{
	static int a[M]= {12,0,6,16,23,56,80,100,110,115};
	int n,low,mid,high,found;
	low = 0;
	high= M-1;
	found = 0;
	printf("Please input a number to be searched:");
	scanf("%d",&n);

	while(low <= high)
	{
		mid = (low + high)/2;
		
		if (n==a[mid])
		{
			found = 1;break;
		}
		else if (n>a[mid])
		{
			low= mid + 1;
		}
		else 
		{
			high= mid -1;
		}		
	}

	if (found == 1)
	{
		printf("The index of %d is %d \n",n,mid);
	}
	else
	{
		printf("There is not %d \n",n);
	}
}

[liangjian@localhost ~]$ gcc test3.c &&./a.out 
Please input a number to be searched:115
The index of 115 is 9 
[liangjian@localhost ~]$ gcc test3.c &&./a.out 
Please input a number to be searched:66
There is not 66 
[liangjian@localhost ~]$ 
举报

相关推荐

0 条评论