二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
public class Solution {
public static int BinarySearch(int[] sz,int key){
int low = 0;
int high = sz.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
if(sz[middle] == key){
return middle;
}else if(sz[middle] > key){
high = middle - 1;
}else {
low = middle + 1;
}
}
return -1;
}
}
范例:
package com.ldw.test;
public class test3 {
public static void main(String[] args){
int[] array = {1,2,4,6,8,10,24,45};
int a = HalfFind(array, 10);
if(a == -1){
System.out.println("not find this one");
}else {
System.out.println("=====" + a);
}
}
public static int HalfFind(int[] array, int key){
int low = 0;
int high = array.length - 1;
while(low <= high){
int middle = (low + high) / 2;
if(array[middle] == key){
return middle;
}else if(array[middle] > key){
high = middle - 1;
}else{
low = middle + 1;
}
}
return -1;
}
}