【数据结构】二分查找

#include<iostream>
#include<algorithm>
using namespace std;
//自己写
typedef struct  LNode
{
	LNode *left;
	LNode *right;
	int Length;
	int Element[50];
}LNode,*Linklist;
int BinartSearch(Linklist Tbl,int k)
{
	int left, right, mid, NoFound = -1;
	left = 1;
	right = Tbl->Length;
	while (left <= right)
	{
		mid = (left + right) / 2;
		if (k < Tbl->Element[mid])
			right = mid - 1;
		else if (k > Tbl->Element[mid])
			left = mid + 1;
		else
			return mid;
	}
	return NoFound;
}
//stl
int Elem[50];
int a = binary_search(Elem, Elem + 50, 5);
int main()
{
	int a[100] = { 4,10,11,30,69,70,96,100 };
	int b = binary_search(a, a + 9, 4);//查找成功,返回1
	cout << "在数组中查找元素4,结果为:" << b << endl;
	int c = binary_search(a, a + 9, 40);//查找失败,返回0
	cout << "在数组中查找元素40,结果为:" << c << endl;
	int d = lower_bound(a, a + 9, 10) - a;
	cout << "在数组中查找第一个大于等于10的元素位置,结果为:" << d << endl;
	int e = lower_bound(a, a + 9, 101) - a;
	cout << "在数组中查找第一个大于等于101的元素位置,结果为:" << e << endl;
	int f = upper_bound(a, a + 9, 10) - a;
	cout << "在数组中查找第一个大于10的元素位置,结果为:" << f << endl;
	int g = upper_bound(a, a + 9, 101) - a;
	cout << "在数组中查找第一个大于101的元素位置,结果为:" << g << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值