C語言折半算法/二分查找算法/數字掃雷算法(binary search algorithm、digital minesweeping algorithm for C)


 

最近在系統學習C語言語法,看了B站上比特老師的C語言學習視頻來加強學習,里面的課程不僅有教學還有作業的講解,確實不錯,其中老師在分支和循環章節中講到了折半查找算法或者說二分查找算法,自己寫了實現代碼,也看了老師代碼,統統寫出來,分享給大家~該算法的語法簡單,更值得學習的是算法思路(也是老師說的話)~

(1)本人寫的認為是標准的折半算法、二分查找算法、數字掃雷游戲算法。

 1 #define _CRT_SECURE_NO_WARNINGS 1
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <math.h>
 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 <stdio.h>
 3 #include <stdlib.h>
 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/C++語言,大家在掌握python的基礎上,如果想要提升實戰項目落地經驗,獲取更高的工資,也要系統學習下C,會給你帶來多多收益的~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM