转载请注明出处:http://blog.csdn.net/droyon/article/details/8680044
分治法和折半查找都是时间复杂度为O(log N)。
折半查找:给定一个整数X和整数数组A[],元素为a,b,c....n,后者这个数列已经预先排序并在内存中,求下标i使得A[i] =X,如果数组内不存在X,则返回-1.
解法:
如果按照数组的内容,从左到右顺序扫描一遍,那么将要花费线性时间。并且没有用到数组已经排序的事实。
折半查找是解决这类问题的一个好办法,首先检查数组居中的元素是否和X相等,如果相等,那么就找到了,如果不在,则比较X和数组中居中的元素,如果大于居中的元素,那么我们检查数列的有半部分,同理检查左半部分。
案例:
package 折半查找;
public class HalfRequery {
public static void main(String args[]){
int[] values = new int[]{1,23,56,-45,23,98,56,-93};
int X = 56;
int getReturn = getReturnValue(values, X);
System.out.println("getReturn:"+getReturn+"---------------");
}
private static int getReturnValue(int[] array,int X){
int low = 0;
int high = array.length;
int returnValue = -1;
while(low <= high){
int center = (low + high)/2;
if(array[center]<X){
low = center + 1;
}else if(array[center]>X){
high = center - 1;
}else {
return array[center];
}
}
return returnValue;
}
}
运行结果:
getReturn56---------------