二分查找算法
实现代码
public int bsearch ( int [ ] a, int n, int value) {
int low = 0 ;
int high = n - 1 ;
while ( low <= high) {
int mid = ( low + high) / 2 ;
if ( a[ mid] == value) {
return mid;
} else if ( a[ mid] < value) {
low = mid + 1 ;
} else {
high = mid - 1 ;
}
}
return - 1 ;
}
主要注意点
退出循环的条件时是low<=high,而不是low<high mid的取值如果写成(low+high)/2,在数据量很大的时候会发生内存溢出的问题,一般写成low+(high-low)/2或者直接采用位计算low+((high-low)>>1) low和high的更新必须写成mid-1和mid+1,如果写成low=mid或者high=mid,会造成无法跳出循环(比如当low和high相等的时候)。
二分查找算法变形问题
查找第一个等于给定值的元素
实现代码
public int binarySearch_demo1 ( int [ ] a, int n, int value) {
int low = 0 ;
int high = n - 1 ;
while ( low <= high) {
int mid = low + ( ( high - low) >> 1 ) ;
if ( a[ mid] > value) {
high = mid - 1 ;
} else if ( a[ mid] < value) {
low = mid + 1 ;
} else {
if ( mid == 0 || a[ mid- 1 ] != value) return a[ mid] ;
high = mid - 1 ;
}
}
return - 1 ;
}
查找最后一个等于给定值的元素
实现代码
public int binarySearch_demo2 ( int [ ] a, int n, int value) {
int low = 0 ;
int high = n - 1 ;
while ( low <= high) {
int mid = low + ( ( high - low) >> 1 ) ;
if ( a[ mid] > value) {
high = mid - 1 ;
} else if ( a[ mid] < value) {
low = mid + 1 ;
} else {
if ( mid == n- 1 || a[ mid + 1 ] != value) return a[ mid] ;
low = mid + 1 ;
}
}
return - 1 ;
}
查找第一个大于等于给定值的元素
实现代码
public int binarySearch_demo3 ( int [ ] a, int n, int value) {
int low = 0 ;
int high = n - 1 ;
while ( low <= high) {
int mid = low + ( ( high - low) >> 1 ) ;
if ( a[ mid] >= value) {
if ( mid == 0 || a[ mid - 1 ] < value) return a[ mid] ;
high = mid - 1 ;
} else {
low = mid + 1 ;
}
}
return - 1 ;
}
查找第一个小于等于给定值的元素
实现代码
public int binarySearch_demo4 ( int [ ] a, int n, int value) {
int low = 0 ;
int high = n - 1 ;
while ( low <= high) {
int mid = low + ( ( high - low) >> 1 ) ;
if ( a[ mid] > value) {
high = mid - 1 ;
} else {
if ( ( mid == n - 1 ) || ( a[ mid + 1 ] > value) ) return mid;
else low = mid + 1 ;
}
}
return - 1 ;
}