二分法查找---java版

比较简单,直接上代码了

package cn.nrsc.algorithm;

/**
 * 
 * @author 孙川 二分查找就是在一堆已经排好序的数组中通过折半规则查找出某个数在数组中的位置
 *
 */
public class BinarySearch {
	public static void main(String[] args) {
		int[] arr = { -1, 0, 1, 2, 5, 8, 22, 22, 23, 38, 49, 65, 76, 972 };

		int num = 23; // 在数组中查找的数
		int index = nonBinarySearch(arr, num, 0, arr.length - 1);
		System.out.print(num + "在数组中的索引为: " + index);

	}

	// 非递归方式
	private static int nonBinarySearch(int[] arr, int target, int left, int right) {

		while (left < right) {
			int middle = (left + right) / 2; // 中间值所在的索引
			if (target == arr[middle])
				return middle;
			else if (target < arr[middle]) // 目标值比中间值还小,肯定在中间值的左边
				right = middle - 1; // 将右指针指向middle-1
			else // 肯定在右边
				left = middle + 1; // 将左指针指向middle+1
		}
		return -1; // 没找到
	}

	// 递归方式
	private static int binarySearch(int[] arr, int target, int left, int right) {
		// 没找到
		if (left > right)
			return -1;

		int middle = (left + right) / 2;// 中间值所在的索引
		if (target == arr[middle])
			return middle;
		else if (target < arr[middle]) // 目标值比中间值还小,肯定在中间值的左边
			return binarySearch(arr, target, left, middle - 1); // 去左边找
		else
			return binarySearch(arr, target, middle + 1, right); // 去右边找
	}

}

猜你喜欢

转载自blog.csdn.net/nrsc272420199/article/details/82886896