二分搜索
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 5 using namespace std; 6 7 //二分搜索 8 9 int binarySearch(int a[],int length,int data) { 10 int left = 0; 11 int right = length - 1; 12 13 int index = -1; 14 while (left <= right) 15 { 16 int mid = (left + right) / 2; 17 if(a[mid] > data) { 18 right = mid - 1; 19 } else if(a[mid] < data) { 20 left = mid + 1; 21 } else { 22 index = mid; 23 break; 24 } 25 } 26 27 return index; 28 } 29 30 int main() { 31 int a[] = {1,2,3,4,5}; 32 int index = binarySearch(a,5,3); 33 34 cout<<index<<endl; 35 }
posted on 2021-01-08 16:53 wlqsmiling 阅读(51) 评论(0) 编辑 收藏 举报