折半查找

#include <stdio.h>

int main()
{
	int m[10] = {-3,4,7,9,13,45,67,89,100,180};
	int low = 0, high = 10 - 1, mid; //low起始位置 high末位置
	int a, i, k = -1;   //k保存位置 a为要查找的数
	printf("输入要查找的数:");
	scanf_s("%d", &a);
	while (low <= high)
	{
		mid = (low + high) / 2;   //确定中心mid的位置
		if (a < m[mid]) high = mid - 1;
		else
			if (a > m[mid])low = mid + 1;
			else { k = mid; break; }
	}
	if (k >= 0)printf("index = %d", k);
	else printf("Not be found!");
}

posted @ 2023-04-21 22:23  258333  阅读(12)  评论(0编辑  收藏  举报