Common Algorithms - Binary Search (non-recursive)

Binary search (non-recursive)

basic introduction

Also known as binary search binary search (Binary Search), it is a high efficient search method. However, binary search requires linear table must sequential storage structure , and the elements in the table by a keyword ordered .

  • First, assume that the table element is by ascending order , the key intermediate position table recorded with the lookup key comparison, if the two are equal, then the lookup is successful; otherwise, use of the recording table into an intermediate position before and after the two sub-tables, if keywords middle position of the recording is greater than the search key, then look further before a child table, or further search after a child table. The process is repeated until the record satisfies the condition is found, the search is successful, or until the child table does not exist, at which time search is unsuccessful.

The number of comparisons

a<log2n<b

Operator time complexity hair

O(n)=O(log2n)

Code

In arr = {1, 3, 8, 10, 11, 67, 100} Example

public class BinarySerch {
	public static void main(String[] args) {
		int[] arr = { 1, 3, 8, 10, 11, 67, 100 };
		// 测试二分查找
		int index = binarySearch(arr, 1);
		System.out.println("index=" + index + "  值【" + arr[index] + "】");
	}
	/**
	 * @Method_Name:binarySearch
	 * @Description: 非递归实现二分查找
	 * @param arr
	 *            数组
	 * @param target
	 *            要查找的数
	 * @return int 返回对应下标 没有找到返回-1
	 */
	public static int binarySearch(int[] arr, int target) {
		int left = 0;
		int right = arr.length - 1;
		while (left <= right) {
			int mid = (right + left) / 2;
			if (arr[mid] == target) {
				return mid;
			} else if (arr[mid] > target) {
				right = mid - 1;
			} else {
				left = mid + 1;
			}
		}
		return -1;
	}
}
Published 39 original articles · won praise 31 · views 6098

Guess you like

Origin blog.csdn.net/lu_long/article/details/104107472