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

【C】折半查找法

程序员文章站 2024-03-20 18:20:22
...
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>

void main()
{
	int arr[] = { 1,3,5,7,9,11,13,15,17,19 };
	int key=0,mid=0, left = 0, right = sizeof(arr) / 4 - 1;
	printf("请输入哟个要查找的数字:");
	scanf("%d", &key);
	for (left = 0; left <=right; )
	{
		mid = (left + right) / 2; 
		if (key>arr[mid])
		{
			left = mid+1;
		}
		else if (key < arr[mid])
		{
			right = mid-1;
		}
		else
		{
			break;
		}
	}	
	if(left<=right)
		printf("找到了\n"); 
	else
	{
		printf("没找到\n");
	}
	system("pause");
}