C语言折半算法/二分查找算法/数字扫雷算法(binary search algorithm、digital minesweeping algorithm for C)
最近在系统学习C语言语法,看了B站上比特老师的C语言学习视频来加强学习,里面的课程不仅有教学还有作业的讲解,确实不错,其中老师在分支和循环章节中讲到了折半查找算法或者说二分查找算法,自己写了实现代码,也看了老师代码,统统写出来,分享给大家~该算法的语法简单,更值得学习的是算法思路(也是老师说的话)~
(1)本人写的认为是标准的折半算法、二分查找算法、数字扫雷游戏算法。
1 #define _CRT_SECURE_NO_WARNINGS 1
2 #include
3 #include
4 #include
5
6 int main() {
7 int value1 = 0; // 数值下限
8 int value2 = 100; // 数值下限
9 int target = 51; // 目标值
10 int num = value2 - value1 + 1;
11 int index1 = 0;
12 int index2 = num - 1;
13 int current_index = num / 2; // 当前索引值
14 int current_value = (value1 + value2) / 2; // 当前索引对应的值
15 int count = 1; // 统计计算次数
16 while (current_value != target)
17 {
18 count = count + 1; // 计算次数+1
19 // 如果当前值比目标值大,那么就更新上限
20 if (current_value > target) {
21 value2 = current_value;
22 index2 = current_index;
23 }
24 // 如果当前值比目标值小,那么就更新下限
25 else {
26 value1 = current_value;
27 index1 = current_index;
28 }
29 // 重新更新当前索引值和当前索引值对应的值再次进行计算
30 current_index = (index1 + index2) / 2;
31 current_value = (value1 + value2) / 2;
32 }
33 printf("target index = %d \n", current_index);
34 printf("count = %d \n", count);
35 float count_log = log2(100);
36 printf("Maximun number of count = log2(num) = %f \n", count_log);
37
38 return 0;
39 }
运行结果 :
写完这个代码本人深有体会,之前几乎都是用python写算法,只要逻辑思路明确了,写起代码来那是遛遛遛,特别容易的事情,但是在用C语言写算法的时候,在还不太熟悉C的情况下,连实现起用一个变量值定义数组的长度就很吃力,后来我写这个代码的时候就换了思路避免使用先创建一个动态数组的方法,本人调试的了一些数据都可以 ,但是如果亲们在运行时有发现其他问题的,欢迎大家指正批评!
(2)比特老师视频中实现的代码,该代码的题目是:
在一个有序数组中查找具体的某个数字n。编写int binsearch(int x, int v[], int n);
功能:在v[0]<=v[1]<=v[2]<=...<=v[n-1]的数组中查找x。
解题思路推荐使用算法:折半查找算法、二分查找算法,比如找一个给定范围的数字,就可以使用这种方法每一次都缩小一半的查找范围, 因为前提是这个序列是有序的,这种算法找的最多次数是log2(n)次的向上取整。
1 #define _CRT_SECURE_NO_WARNINGS 1
2 #include
3 #include
4
5 int main() {
6 int arr[] = { 1, 2, 3, 4, 5, 6, 8, 9, 10, 11 };
7 int k = 6; // 定义要找的值
8 int sz = sizeof(arr) / sizeof(arr[0]); // 计算元素个数
9 int left = 0; // 左下标
10 int right = sz - 1; // 右下标
11 while (left <= right) {
12 int mid = (left + right) / 2;
13 if (arr[mid] > k) {
14 right = mid - 1;
15 }
16 else if (arr[mid] < k) {
17 left = mid + 1;
18 }
19 else {
20 printf("找到了,下标是:%d \n", mid);
21 break;
22 }
23 }
24 if (left > right) {
25 printf("找不到 \n");
26 }
27 }
运行结果:
本人主要从事的是算法相关的工作,主打用的是python语言,但是在面试中面试官提点说掌握C/C++的话,工资直接翻一倍,算法中使用C主要涉及到项目的实际落地中代码的优化,毕竟Python的性能是不适合部署到设备中的,所以决定系统学习C语言,大家在掌握python的基础上,如果想要提升实战项目落地经验,获取更高的工资,也要系统学习下C,会给你带来多多收益的~