代码之美中的二分搜索算法--Java版

很多人写二分搜索的时候,都会存在一些纰漏,前段时间看到代码之美里面有一段程序,总结了二分搜索

package com.algorithms.binsearch;

public class BinSearch {

	// expert experience, absolute right !
	public static int find(String[] keys, String target) {
		int high = keys.length;
		int low = -1;
		
		while (high - low > 1) {
			int probe = (high + low) >>> 1; //avoid overflow
			if (keys[probe].compareTo(target) > 0) {
				high = probe;  
			} else 
				low = probe;
		} //why not break in while loop ?
		
		if (low == -1 || keys[low].compareTo(target) != 0) 
			return -1;
		else 
			return low;
	}
}


你可能感兴趣的:(算法,二分搜索)