程序说明笔者都写在注释里面了,思想很简单,但是写代码的时候还是要注意一些细节,比如特殊情况的处理,防止死循环等
- package sixth;
- public class HalfSearch {
- /**
- * 这般查找
- * @param array 要查找的数组,数组必须是有序的
- * @param num 要查找的数
- * @return 返回的是数组所在数组的索引
- */
- public int halfSearch(int[] array,int num){
- //l表示低位游标,h表示高位游标,index指示之间位置的索引
- int index,l=0,h=array.length;
- index=array.length/2;
- //先排除首位与尾位两个位置,这两个位置比较特殊,用折半查找需要特殊指出
- if(num==array[0])
- {
- return 0;
- }
- else if(num==array[array.length-1])
- {
- return array.length-1;
- }
- //开始折半的循环,注意中断条件,防止死循环
- while((l+1)!=h)
- {
- if(num==array[index])
- {
- return index;
- }
- else if(num>array[index])
- {
- l=index;
- index=(h+l)/2;
- }
- else
- {
- h=index;
- index=(h+l)/2;
- }
- }
- return -1;
- }
- public static void main(String[] args) {
- int count=100;
- int[]array = new int[100];
- Tool.initArray(count, array);
- HalfSearch hs=new HalfSearch();
- System.out.println(hs.halfSearch(array, 100));
- }
- }