1.给定一个有序(不降序)数组a,求任意一个i使得a[i]等于v,不存在返回-1
int bisearch(int[] a, int v){ int low = 0,high = a.length-1,t; while(low<=high){ t = low+(high-low)/2; if(a[t]==v) return t; else if(a[t]>v){ low = t+1; }else{ high = t-1; } } return -1; }
2. 给定一个有序(不降序)数组a,求最小的i使得a[i]等于v,不存在返回-1
int bisearch(int[] a, int v){ int low = 0,high = a.length-1,t; while(low<high){ t = low+(high-low)/2; if(a[t]<v){ low = t+1; }else{ //相等时仍要往下标为0处走 high = t; } } if(a[high]==v) return (high); else return -1; }
3.给定一个有序(不降序)数组a,求最大的i使得a[i]等于v,不存在返回-1
int bisearch(int[] a, int v){ int low = 0,high = a.length-1,t; while(low<high-1){ t = low+(high-low)/2; if(a[t]>v){ high = t-1; }else{ low = t; } } if(a[low+1]==v) System.out.println(low+1); else if(a[low]==v) System.out.println(low); else System.out.println(-1); }