java中数据结构二分查法

数据结构和算法是一个程序的灵魂,优化程序的主要手段。在查询里,分为静态查询和动态查询。有序表是静态查询的一种,在。有序表查找过程中,可以用折半查找实现。代码如下:
Java代码 
package Array; 
/**
* 折半查找
* @author luozhong
*
*/ 
public class ArrayTest_lesson1 { 
    //定义数组 
    int array[]=new int[]{0,1,2,3,4,5,6,7,8,9}; 
    //定义三个变量 
    int low, mid,high; 
     
    public static void main(String args[]){ 
         
        new ArrayTest_lesson1().init(9); 
    } 
    public void init(int temp){ 
        //此变量指着第一个元素 
        low=1; 
        //此变量指着末元素 
 
        high=array.length; 
        //调用查询方法 
        int key=Index(low,high,temp); 
         
        System.out.println("查询结果为:"+key); 
         
         
    } 
    private int Index(int low2, int high2, int temp) { 
          //判断循环的条件 
        while(low2<=high2){ 
             
            mid=(low2+high2)/2; 
            //判断是否与查询值相等,返回索引位置 
            if(temp==array[mid]) return mid; 
            //如果小于数组元素 
            else if(temp<array[mid])  high2=mid-1; 
            ////如果大于数组元素 
            else low2=mid+1; 
             
        } 
        return 0; 
    } 
 


          折半查找的性能分析,他查找的过程可用二叉树来描述。折半查找在查找不成功时候和给定值进行比较关键字个数最多也不超过{logn/log2}+1.
          假设表中每个记录查找概率相等(p=1/n),则查找成功时的折半查找的平均查找长度如图:

猜你喜欢

转载自lvwenwen.iteye.com/blog/1486996