二分法查找的一个简单实现

public class SearchItem {

	public static void main(String[] args) {

		int[] array = { 3, 5, 7, 23, 54, 57, 60, 78, 89, 90, 101, 210, 333, 456 };

		System.out.println(binarySearch(array, 456));

	}

	/**
	 * 二分法查找
	 *
	 * @param array
	 *            预排序数组
	 * @param item
	 *            要查找的数值
	 * @return 定位索引,未找到返回 -1
	 */
	private static int binarySearch(int[] array, int item) {
		int startIndex = 0;
		int endIndex = array.length - 1;

		if (item > array[endIndex] || item < array[startIndex]) {
			return -1;
		}

		int middleIndex = (startIndex + endIndex) / 2;
		while (array[middleIndex] != item && startIndex <= endIndex) {

			if (array[middleIndex] > item) {
				endIndex = startIndex - 1;
			} else {
				startIndex = startIndex + 1;
			}
			middleIndex = (startIndex + endIndex) / 2;
		}

		return array[middleIndex] == item ? middleIndex : -1;
	}
}

 

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