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

折半查找原理(C++)

程序员文章站 2022-03-15 11:41:17
...
#include<stdio.h>
#include<iostream>
using namespace std;

int find(int a[],int num)
{
	int low=0;
	int high=8;
	int mid=(low+high)/2;
	while(a[mid]!=num)
	{
		if(high<=low)
			return -1;
		cout<<"high="<<high<<endl;
		cout<<"low="<<low<<endl;
		cout<<"mid="<<mid<<endl;
		if(num>a[mid]) low=mid+1;
		else high=mid-1;
		mid=(high+low)/2;

	}
	/*while(high>=low)
	{
		cout<<"high="<<high<<endl;
		cout<<"low="<<low<<endl;
		cout<<"mid="<<mid<<endl;
		if(a[mid]==num)return mid;
		else if(a[mid]>num)high=mid-1;
		else low=mid+1;
		mid=(high+low)/2;
	}*/
	return mid;
}
void main()
{
	int nums[10]={1,2,3,4,5,6,7,8,9};
	int pos;
	int num;
	cin>>num;
	pos=find(nums,num);
	cout<<pos<<endl;
}

相关标签: 折半查找