博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
折半查找函数(from 《The C Programming Language》)
阅读量:6983 次
发布时间:2019-06-27

本文共 1393 字,大约阅读时间需要 4 分钟。

该函数用于判定已排序的数组array中是否存在某个特定的值value。这里假定数组元素以升序排列,如果数组array中包含value,则函数返回value在array中的位置(介于0~n-1之间的一个整数);否则,该函数返回-1。

在折半查找时,首先将value与数组array的中间元素进行比较,如果value小于中间元素的值,则接下来在该数组的前半部分查找;否则,在该数组的后半部分查找。在这两种情况下,下一步都是将value与所选部分的中间元素进行比较。这个过程一直进行下去,直到找到指定的值或者查找范围为空。

1 #include 
2 3 #define N 10 4 5 //函数声明 6 int binsearch(int value, int array[], int n); 7 8 int main(void) 9 {10 int array[N] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9};11 int value = 5;12 int ret;13 14 ret = binsearch(value, array, N);15 if (ret == -1)16 printf("This value does not exist in the array.\n");17 else18 printf("The value in the array is in position %d.\n", ret);19 20 return 0;21 }22 23 /* binsearch函数:在array[0]~array[n-1]中查找value */24 int binsearch(int value, int array[], int n)25 {26 int low, high, mid;27 28 low = 0;29 high = n - 1;30 31 while (low < high)32 {33 mid = (low + high) / 2;34 if (value < array[mid])35 high = mid - 1;36 else if (value > array[mid])37 low = mid + 1;38 else39 return mid;40 }41 return -1;42 }43 /*44 The output results in Code::Blocks 10.0545 ---------------------------------------------46 The value in the array is in position 5.47 ---------------------------------------------48 */

 

转载于:https://www.cnblogs.com/hquljb/p/3342895.html

你可能感兴趣的文章
Dreamweaver PHP代码护眼配色方案
查看>>
记Booking.com iOS开发岗位线上笔试
查看>>
MVC之ActionFilterAttribute自定义属性
查看>>
IE6/IE7下:inline-block解决方案
查看>>
NuGet在Push的时候提示“远程服务器返回错误:(403)已禁用”问题解决
查看>>
FindBugs插件
查看>>
innoDB 存储引擎
查看>>
H5调用Android播放视频
查看>>
ASP.NET Aries JSAPI 文档说明:AR.DataGrid、AR.Dictionary
查看>>
1024程序员节获奖通知
查看>>
9大方法为云安全保驾护航
查看>>
Android Studio Linking an external C++ project 时候 报Invalid file name. Expected: CMakeLists.txt
查看>>
MYSQL数据库注释
查看>>
管理11gRAC基本命令 (转载) 很详细
查看>>
数据库 SQL语法一
查看>>
实现物体绕不同轴旋转,并可以外部调用的函数
查看>>
UDP socket 设置为的非阻塞模式
查看>>
Atitit截屏功能的设计解决方案
查看>>
mysql通过binlog日志来恢复数据
查看>>
JWT实现token-based会话管理
查看>>