1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include<iostream>
using namespace std;
bool check1(int index,int tar){ if(index < tar)return true; return false; } bool check2(int index,int tar){ if(index > tar)return true; return false; } int binasearch_lower(int n[],int size,int tar){ int left=0,right=size; while (left+1<right) { int mid = (left+right)/2; if(check1(n[mid],tar)){ left=mid; }else right=mid; } if(n[right]==tar)return right; else return -1; }
int binasearch_upper(int n[],int size,int tar){ int left=0,right=size; while (left+1<right) { int mid = (left+right)/2; if(check2(n[mid],tar)){ right=mid; }else left=mid; } if(n[left]==tar)return left; else return -1; } bool testsearch(int n[],int size,int tar){ int l=0,r=size; while(l+0<=r){ int mid = (l+r)/2; if(n[mid]==tar)return true; else{ if(n[mid]>tar)r=mid-1; else l=mid+1; } } return false; }
int main(){ int a[12]={0,1 ,3, 3, 3, 5, 7, 9, 11, 13, 15}; int b[8]={1,2,3,4,5,6,7,8}; cout<<binasearch_lower(a,12,9)<<' '<<binasearch_upper(a,12,9)<<endl; cout<<testsearch(b,8,4); }
|