简单高效二分查找算法
2023-04-18 12:57:49 时间
首先介绍下对二分查找算法的理解:
目的:
从一组有序序列中查找一给定数的位置。
成员:
1.有序序列,假定为数组。
2.任意数
思路:
1.取数组中间的数与给的任意数做比较,
2.如果中间数大于任意数,则以中间数为分界一分为二,取左边做新的数组,右边的丢掉。
拿新的数组和任意数重复1的操作。
3.如果中间数小于任意数,则以中间数为分界一分为二,取右边做新的数组,左边的丢掉。
拿新的数组和任意数重复1的操作。
python代码如下:
def binary_search(arr,item): low=0 high=len(arr)-1 while low<=high: mid = int((high+low) / 2) guess = arr[mid] if guess == item: return mid if guess > item: high=mid-1 else: low=mid+1 return None my_list = [1,3,5,7,9] print (binary_search(my_list,3)) print(binary_search(my_list,-1))
运行结果:
1
None
C#代码如下:
using System; namespace BinarySearch { class Program { static void Main(string[] args) { int[] arr = new int[] { 1, 3, 5, 7, 9 }; var result = Search(arr, 3); ShowMessage(result); result = Search(arr, -1); ShowMessage(result); Console.Read(); } private static void ShowMessage(int result) { Console.WriteLine($"result位置 " + (result == -1 ? "未找到" : result.ToString())); } static int Search(int[] arr,int item) { int low=0,mid=0, high = arr.Length - 1; while(low <= high) { mid = (high + low) / 2; if (arr[mid] == item) return mid; if (arr[mid] > item) high = mid - 1; else if(arr[mid] < item) low = mid + 1; else return -1; } return -1; } } }
运行结果:
result位置 1
result位置 未找到
相关文章
- AI助力“科技冬奥”,优必选机器人赴冰雪之约
- 用tailwindcss适配暗黑模式竟如此简单
- Mycat HA(高可用) 与 LB(负载均衡)18
- Mycat HA(高可用) 与 LB(负载均衡)19
- kubernetes核心实战(七)--- job、CronJob、Secret
- 中国互联网企业,几乎都有外资背景,这说明了什么?以后呢?
- Mycat web 基础1
- Mycat web 基础2
- 混合工作模式下,寻找IT人才的五个关键
- Mycat web 基础3
- Mycat web 基础4
- 解决'Function.caller used to retrieve strict caller'报错
- 一周 8k Star 的 Notion 开源替代品 AppFlowy 发布了!
- Rollup作者新作: Svelte Cubed!VR/AR 指日可待?
- 回顾2021 Github最受欢迎的前端项目,谷歌 zx 位居榜首!
- ble功耗优化——连接参数更新
- Linux中断虚拟化(一)
- 直击春运:那些你看得见和看不见的技术博弈
- KEIL编译后程序的大小,Code、RO-data、RW-data、ZI-data的关系
- 因是反竞争的并违反了反垄断法,Sold by Amazon将被永久关闭