二分查找c++
相信对于二分查找的原理大家已经明白,接下来就是代码实现了
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 }
这样,这一个二分查找就完美的实现了!!!
更多代码请进入: https://github.com/tomatoschool