package com.yuan.alg; /** * @author yuan *这个程序是演示折半查找的例子。 *该算法是用递归实现的。 *前提条件是该数组必须是有序的。 */ public class a001 { /** * */ public a001() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] Array={1,4,5,7,8,9,10,90,99,100}; //有序数列 int findvalue=101; //查找值。 //调用递归二叉树查找方法,将结果返回给result。 int result=binarysearch(Array,0,Array.length-1,findvalue); if(result!=-1) //如果有结果,输出结果。 { System.out.println("该数的下标是:"+result); System.out.println("/n该数是第"+(result+1)+"个数!"); } else //否则,输出提示 System.out.println("该值不存在!"); } /** * binarysearch方法实现了折半查找的功能,也和二叉树查找相似。 * 这是一个递归二叉树查找,在性能上有待提高,查找速度很快,特别适合有序的 * 数列的查找。 * 该算法的主旨:通过比较中间数与目标值的大小来改变查找方向。 * 若中间数比目标值大,向前查找;反之,向后查找。 * 不断执行这个方法,即递归,直到中间数与目标值相等;反之,若没有匹配的数,则返回 * null。 * * */ public static int binarysearch(int array[],int first,int last,int value) { int index; if(first>last) //first>last,不符合查找的条件。 { return -1; } else { int mid=(first+last)/2; //求mid的值,为查找提供条件。 if(value==array[mid]) //值与中间值匹配。 { index=mid; //接受mid。 } else if(value<array[mid]) //若小,则向前查找 return binarysearch(array,first,mid-1,value); else //若大,则向后查找。 return binarysearch(array,mid+1,last,value); } return index; //返回一个index,即结果。 } }