首页 > 代码库 > [算法]各种二叉搜索
[算法]各种二叉搜索
1,给定一个有序数组values,求任意一个i使得values[i]等于v,不存在返回-1
int search(int* values,int len,int key){ if(!values || len <=0) return -1; int low=0; int high=len-1; while(low<=high) { int mid =(low+high)/2; if(values[mid]==key) return mid; else if(values[mid]>key) high=mid-1; else low = mid +1; } return -1;}
2,给定一个有序数组values,求最小的i使得values[i]等于v,不存在返回-1
int searchFirst(int * values,int len,int key){ if(!values || len <=0) return -1; int low=0; int high=len-1; while(low<=high) { int mid =(low+high)/2; if(values[mid]==key) { if(mid==0) return mid; else if(values[mid-1]<key) return mid; else high=mid-1; } else if (values[mid]>key) high=mid-1; else low=mid+1; } return -1;}
3,给定一个有序数组values,求最大的i使得values[i]等于v,不存在返回-1
int searchLast(int* values,int len,int key){ if(!values || len <=0) return -1; int low=0; int high=len-1; while(low<=high) { int mid =(low+high)/2; if(values[mid]==key) { if(mid==len-1) return mid; else if(values[mid+1]>key) return mid; else low=mid+1; } else if (values[mid]>key) high=mid-1; else low=mid+1; } return -1;}
4,给定一个有序数组values,求最大的i使得values[i]小于v,不存在返回-1
int searchLargestSmallThan(int* values,int len,int key){ if(!values || len <=0) return -1; int low=0,high=len-1; while(low <= high){ int mid = (low+high)/2; if(values[mid]>=key) high=mid-1; else{ if(mid<len-1 && values[mid+1]>=key) return mid; else low=mid+1; } } return -1;}
4,给定一个有序数组values,求最小的i使得values[i]大于v,不存在返回-1
int searchSmallestLargeThan(int* values, int len,int key){ if(!values || len <=0) return -1; int low=0,high=len-1; while(low <= high){ int mid = (low+high)/2; if(values[mid]<=key) low=mid+1; else{ if(mid>0 && values[mid-1]<=key) return mid; else high=mid-1; } } return -1;}
[算法]各种二叉搜索
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。