前提:顺序数组、依赖顺序结构,其查找是按照下表随机访问,其他存储结构是不适合的,数据量太小也是不适合的,数据量太大也不行,因为其需要连续内存
思想:分制 O(logn)
/*
* 最简单的二分查找,假设值没有重复的
*/
public static int secondSplitSearch(int[] source,int left,int right,int val) {
if(right < left) {
return -1;
}
int mid = left + (right-left)/2;
if(val == source[mid]) {
return mid;
}else if(val>source[mid]) {
return secondSplitSearch(source,mid+1,right,val);
}else{
return secondSplitSearch(source,left,mid-1,val);
}
}
/*
* 假设值有重复的,查找第一只等于给定值的元素
*/
public static int secondSplitSearchFirst(int[] source,int left,int right,int val) {
if(right < left) {
return -1;
}
int mid = left + (right-left)/2;
if(val == source[mid]) {
int temp = mid;
for(int i =mid;i>=0;i--) {
if(val == source[i]) {
temp = i;
}else {
break;
}
}
return temp;
}else if(val>source[mid]) {
return secondSplitSearchFirst(source,mid+1,right,val);
}else{
return secondSplitSearchFirst(source,left,mid-1,val);
}
}