c编程语言提供了两种搜索技术。它们如下所示:
线性搜索二分搜索
二分搜索
这种方法只适用于有序列表。给定列表被分成两个相等的部分。给定的关键字与列表的中间元素进行比较。
在这里,可能会发生三种情况,如下所示:
如果中间元素与关键字匹配,则搜索将在此成功结束
如果中间元素大于关键字,则搜索将在左侧分区进行。
如果中间元素小于关键字,则搜索将在右侧分区进行。
立即学习“C语言免费学习笔记(深入)”;
输入 (i/p) – 未排序的元素列表,关键字。
输出 (o/p) –
成功 – 如果找到关键字失败 – 否则
key = 20mid = (low +high) /2
登录后复制
程序1
#includeint main(){ int a[50], n, i, key, flag = 0, low, mid, high; printf("enter the no: of elements:"); scanf ("%d",&n); printf("enter the elements:"); for(i=0; i key) high = mid-1; else low = mid+1; } } if (flag == 1) printf ("search is successful"); else printf("search is unsuccessful"); return 0;}
登录后复制
输出
当上述程序被执行时,它产生以下结果 −
Run 1:enter the no: of elements:5enter the elements:1234115667enter a key element:45search is unsuccessfulRun 2:enter the no: of elements:3enter the elements:123456enter a key element:34search is successful
登录后复制
Program2
给定下面的C程序,通过使用二分查找来找到数组中的最小元素−
#includevoid Bmin(int *a, int i, int n){ int j, temp; temp = a[i]; j = 2 * i; while (j a[j]) j = j + 1; if (temp = a[j]){ a[j / 2] = a[j]; j = 2 * j; } } a[j/2] = temp; return;}int binarysearchmin(int *a,int n){ int i; for(i = n/2; i >= 1; i--){ Bmin(a,i,n); } return a[1];}int main(){ int n, i, x, min; int a[20]; printf("Enter no of elements in an array"); scanf("%d", &n); printf("
Enter %d elements: ", n); for (i = 1; i
输出
当上述程序被执行时,它产生以下结果 −
Enter no of elements in an array5Enter 5 elements:1223344556minimum element in an array is: 12登录后复制
以上就是如何使用二分查找算法在C语言中找到数组中的最小元素?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2587711.html