【小白成长撸】--二分查找
1 /*程序的版权和版本声明部分: 2 **Copyright(c) 2016,电子科技大学本科生 3 **All rights reserved. 4 **文件名:二分查找 5 **程序作用:二分查找 6 **作者:Amoshen 7 **完成日期:2016.10.12 8 **版本号:V1.0 9 */ 10 #include <iostream> 11 12 using namespace std; 13 14 int main(void) 15 { 16 int a[] = {1,2,3,4,5,6,7,8,9}; 17 int lf = 0,rg = 8,mid,x,flag = 1; 18 19 mid = (lf + rg)/2; 20 21 cout << "请输入查找的数:"; 22 cin >> x ; 23 24 for(;lf <= rg;) 25 { 26 if(a[mid] == x) 27 { 28 cout << "x的位置:"<<mid << endl; 29 flag = 0; 30 break; 31 } 32 if(a[mid] > x) 33 { 34 rg = mid - 1; 35 mid = (lf + rg)/2; 36 } 37 if(a[mid] < x) 38 { 39 lf = mid + 1; 40 mid = (lf + rg)/2; 41 } 42 } 43 if(lf == rg && flag) 44 { 45 cout << "查找失败" << endl; 46 } 47 48 return 0; 49 }