二分法模板binary

xiaoxiao2021-02-28  74

#include<iostream> #include<algorithm> using namespace std; int main() { int a[100]= {4,10,11,30,69,70,96,100}; int b=binary_search(a,a+9,4);//查找成功,返回1 cout<<"在数组中查找元素4,结果为:"<<b<<endl; int c=binary_search(a,a+9,40);//查找失败,返回0 cout<<"在数组中查找元素40,结果为:"<<c<<endl; int d=lower_bound(a,a+9,10)-a; cout<<"在数组中查找第一个大于等于10的元素位置,结果为:"<<d<<endl; int e=lower_bound(a,a+9,101)-a; cout<<"在数组中查找第一个大于等于101的元素位置,结果为:"<<e<<endl; int f=upper_bound(a,a+9,10)-a; cout<<"在数组中查找第一个大于10的元素位置,结果为:"<<f<<endl; int g=upper_bound(a,a+9,101)-a; cout<<"在数组中查找第一个大于101的元素位置,结果为:"<<g<<endl; } 1.如果序列中存在该值 int a[10]={1,3,5,7,10,11,13,18,21,30}; int Binary_search(int target) { int left=0,right=9; while(left<=right) { int mid=(left+right)/2; if(a[mid]<target) left=mid+1; else if(a[mid]>target) right=mid-1; else return mid; } } 2.如果序列存在该值,返回该值的下标;如果序列中不存在该值,返回离它最近并且小于它的 下标(也可以返回值)。 int Binary_search(int target) { int left=0,right=9; int index=0; while(left<=right) { int mid=(left+right)/2; if(a[mid]<=target) { left=mid+1; index=mid; } else right=mid-1; } return index; // 若返回值 return a[index] } 3.如果序列存在该值,返回该值的下标;如果序列中不存在该值,返回离它最近并且大于它的 下标 int a[10]= {1,3,5,7,10,11,13,18,21,30}; int Binary_search(int target) { int left=0,right=9; int index=0; while(left<=right) { int mid=(left+right)/2; if(a[mid]<target) left=mid+1; else { right=mid-1; index=mid; } } return index; // 若返回值 return a[index] }
转载请注明原文地址: https://www.6miu.com/read-54130.html

最新回复(0)