java 二分法查询

 

在ansj看到一个二分法查询,不用递归的

public static int binarySearch(WoodInterface[] branches, char c) {
		int high = branches.length - 1;
		if (branches.length < 1) {
			return high;
		}
		int low = 0;
		while (low <= high) {
			int mid = (low + high) >>> 1;
			int cmp = branches[mid].compareTo(c);

			if (cmp < 0)
				low = mid + 1;
			else if (cmp > 0)
				high = mid - 1;
			else
				return mid; // key found
		}
		return -1; // key not found.
	}
 

你可能感兴趣的:(java,二分法)