二分查找算法
通过改变边界位置来进行查找的方法,代码如下:
1 #include <iostream> 2 3 using namespace std; 4 5 6 int search(int *p,int length,int key); 7 int search1(int *p,int length,int key); 8 9 int main() 10 { 11 cout << "Hello world!" << endl; 12 int a[] = {1,2,3,4,5,6,7,8,8,8,9,10,11,12,13,14}; 13 int len = sizeof(a)/sizeof(int); 14 int pos = search1(a,len,8); 15 cout << pos << endl; 16 return 0; 17 } 18 19 int search1(int *p,int length,int key) 20 { 21 int left=0; 22 int right=length-1; 23 while(left<=right) 24 { 25 int mid = (left+right)/2; 26 if(p[mid]>=key) 27 { 28 right = mid-1; 29 }else 30 { 31 left = mid+1; 32 } 33 } 34 if(left<length && p[left]==key) 35 return left; 36 return -1; 37 } 38 39 40 int search(int *p,int length,int key) 41 { 42 int left=0; 43 int right = length -1; 44 45 while(left<=right) 46 { 47 int mid = (left+right)/2; 48 if(p[mid]==key) 49 { 50 return mid; 51 } 52 if(p[mid] > key) 53 { 54 right = mid+1; 55 } 56 if(p[mid]<key) 57 { 58 left=mid-1; 59 } 60 } 61 return -1; 62 }