二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。
public class BinarySearch {
public int[] array;
public static void main(String[] args) {
BinarySearch bin = new BinarySearch();
int[] arr = {1,3,4,5,6};
bin.setArray(arr);
System.out.println(bin.search(3));
}
public void setArray(int[] array){
this.array = array;
}
public int search(int val){
int low = 0;
int pow = array.length - 1;
int middle = 0;
while(true){
middle = (low + pow) /2;
if(array[middle] == val){
return middle;
}else if(low > pow){
return -1;
}else{
if(array[middle] > val){
pow = middle - 1;
}else if(array[middle] < val){
low = middle + 1;
}
}
}
}
}