查找算法之折半查找

 

Posted by     DH on August 15, 2017

思想

折半查找要求较高:

(1)存储节后是数组

(2)数组有序

主要思想是,取中间的记录作为比较对象,假如相等,就返回中间对象的位置,假如小于中间对象,就在左半部分继续查找,否则在右半部分继续查找。

例子

代码

package findMethod;

public class Binserch {

	public static void main(String[] args) {
		
		Binserch binserch = new Binserch();
		
		int [] a = {4,5,6,8,9,10};
		
		System.out.println(binserch.search(a, 10));
		System.out.println(rank(10, a, 0, a.length-1));

	}

	
	public static int rank(int key,int[] arr,int start,int end){  
        if(start >end){  
            return -1;  
        }  
        int mid=(end+start)/2;  
        if(key<arr[mid]){  
            return rank(key,arr,start,mid-1);  
        }else if(key>arr[mid]){  
            return rank(key,arr,mid+1,end);  
        }else{  
            return mid;  
        }  
    }  
	
	
	// 非递归
	public int search(int []a,int target){
		if (a.length == 0 || a == null) {
			return -1;
		}
		
		int low = 0;
		int high = a.length -1;
		int mid = (high + low) /2;
		
		while (low <= high) {
			
			if (a[mid] == target) {
				return mid;
			}
			
			if (a[mid] > target) {
				high = mid -1;
				mid = (low + high) /2;
			}
			
			if (a[mid] < target) {
				low = mid +1;
				mid = (low + high) /2;
			}
		}
		
		return -1;
	}
	
}