二分查找c++
相信對(duì)于二分查找的原理大家已經(jīng)明白,接下來(lái)就是代碼實(shí)現(xiàn)了
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 #include <string> 6 #include <cstdlib> 7 8 using namespace std; 9 10 int a[1000000]; 11 int mid; 12 13 int main() 14 { 15 int N; 16 cin>>N; 17 int i; 18 int left,right; 19 for(i=0;i<N;i++) 20 { 21 cin>>a[i]; 22 } 23 left = 0; 24 right = N-1; 25 int X; 26 cin>>X; 27 while (left<right) 28 { 29 mid=(left + right)/2; 30 if(X>a[mid]) 31 { 32 left = mid+1; 33 } 34 if(X<=a[mid]) 35 { 36 right=mid; 37 } 38 } 39 if(a[left]==X) 40 cout<<"yes"; 41 else 42 cout<<"no"; 43 return 0; 44 }這樣,這一個(gè)二分查找就完美的實(shí)現(xiàn)了!!!
?
更多代碼請(qǐng)進(jìn)入: https://github.com/tomatoschool?
轉(zhuǎn)載于:https://www.cnblogs.com/zxfzxf/p/9558646.html
總結(jié)
- 上一篇: 环球黑卡真的有额度吗?申请这一点就足够
- 下一篇: 小朋友学C++(1)