利用函数进行二分法查找

本文介绍了一种经典的二分查找算法,并通过C语言代码实现了该算法。文章详细展示了如何在一个有序数组中查找指定元素的位置,如果找到则返回该位置,否则返回-1。通过这个例子,读者可以了解到二分查找的基本思想和实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
int binary_search(int arr[],int key,int left,int right)//先定义二分查找的函数
{
	while(left<=right)
	{
		int mid = left+((right-left)>>1);
	
	if(key > arr[mid])
 		{
 			left = mid+1;
 		}
 		else if(key < arr[mid])
 		{
 			right = mid-1;
 		}
 		else
 		{
 			return mid;
 		}
 	}
 	return -1;
 
 }
int main()
{	
	int arr[]={1,2,3,4,5,6,7,8,9,10};//定义一个数组
	int key = 4;//在数组中找的目标数
	
	int sz = sizeof(arr)/sizeof(arr[0]);//数组中有多少个元素
	
	int ret = binary_search(arr,key,0,9);//定义一个接收变量接收返回值
	
	if(ret==-1)
	{
	printf("找不到\n");
	}
	else
	{
		printf("找到了: %d\n",ret);
	}
	
	return 0;
}


### C++ 中实现二分查找的方法 在 C++ 中,可以利用标准模板库 (STL) 提供的功能来执行高效的二分查找操作。对于数组或向量中的元素查找,`std::binary_search`, `std::lower_bound` 和 `std::upper_bound` 是常用的选择。 #### 使用 `std::binary_search` 此函数用于判断给定值是否存在于已排序序列中: ```cpp #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> vec = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; // 首先对容器进行排序 std::sort(vec.begin(), vec.end()); int target = 2; bool exists = std::binary_search(vec.begin(), vec.end(), target); if(exists){ std::cout << "Element found in the array\n"; }else{ std::cout << "Element not found in the array\n"; } return 0; } ``` 上述代码展示了如何通过 `std::binary_search` 来检测目标数值是否存在於已经过排序的数据集中[^1]。 #### 自定义二分查找算法 如果希望更深入理解其工作原理,则可以通过编写自定义版本的二分查找算法来进行学习: ```cpp #include <iostream> #include <vector> bool custom_binary_search(const std::vector<int>& nums, int key) { int low = 0; int high = static_cast<int>(nums.size()) - 1; while(low <= high){ int mid = low + ((high-low)/2); if(nums[mid]==key){ return true; } if(key<nums[mid]){ high=mid-1; } else { low=mid+1; } } return false; } int main(){ std::vector<int> data={0,1,2,3,4,5,6,7,8,9}; int element_to_find=2; bool result=custom_binary_search(data,element_to_find); if(result){ std::cout<<"Element found in the array\n"; }else{ std::cout<<"Element not found in the array\n"; } return 0; } ``` 这段代码实现了基本的二分查找逻辑,并验证了特定整数是否位于预设范围内。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值