比较简单,主要是明白算法思想。
代码:
#include <iostream> #include <cstdlib> using namespace std; int main() { cout<<"/"<<"折半查找"<<"/"<<endl; cout<<"-------------------"<<endl; int arr[10]={1,2,3,4,5,6,7,8,9,10}; int low,high,mid; int key; cout<<"please input the key:"; cin>>key; low=0; high=9; while(low<=high) { mid=(low+high)/2; if(key==arr[mid]) cout<<"the key pos is "<<mid<<endl; if(key<arr[mid]) high=mid-1; else low=mid+1; } cout<<endl; return 0; }
运行截图: