[Detailed] Java implements binary search (binary search)

1. Outline thoughts

       Binary search is also called binary search. The advantage is that the number of comparisons is small and the search speed is fast, but the sequence to be searched is required to be ordered. For the ascending data collection, first find the middle element in the ascending collection, divide the data collection into two subsets, compare the middle element with the key, and return if it is equal to the key. If it is greater than the key, Search in the previous data set, otherwise search in the latter subset until it is found, if not found, return -1;

2. Algorithm idea

① First determine the middle position of the entire search interval mid=low + (high-low)/2;

② Compare the key value to be checked with the key value of the middle position;

  If they are equal, the search is successful;

  If it is greater than, continue the binary search in the second half area.

  If it is less than, continue the binary search in the first half area.

  If the search is successful, return the index of the array where the keyword is located, and return -1 if it is not found.

Note: The calculation of the intermediate value in binary search:

  This is a classic topic. How to calculate the median in binary search? Everyone generally gives two calculation methods:

  • Algorithm 1: mid = (low + high) / 2
  • Algorithm 2: mid = low + (high – low)/2

   At first glance, algorithm one is concise, and after algorithm two is extracted, it is no different from algorithm one. But in fact, the difference is there. In the method of algorithm 1, in extreme cases, (low + high) has the risk of overflow, and then get wrong mid results, leading to program errors. The second algorithm can ensure that the calculated mid must be greater than low and less than high, and there is no overflow problem.

3. Code implementation

package com.it.select;

public class binarySearch {
	
	public static void main(String[] args) {
		
		int[] arr = {1,2,3,4,6,7,10};
		int middle = binarySearch(10, arr, 0, arr.length-1);
		System.out.println(arr[middle]);
	}
	
	// 返回的是要查询数组元素的下标
	public static int binarySearch(int key,int[] array,int left,int right) {
		
		if(key < array[left] || key > array[right] || left > right) {
			return -1;
		}
		
		//取数组下标的中间值
		int mid = left + (right - left)/2;
		if(array[mid] > key) {
			return binarySearch(key, array, left, mid-1);
		}else if(array[mid] < key) {
			return binarySearch(key, array, mid + 1, right);
		}else {
			return mid;
		}
	}
}

4. Algorithm analysis

 The time complexity of binary search is O(log2n)

Guess you like

Origin blog.csdn.net/Sunshineoe/article/details/114883010
Recommended