Java data structure and algorithm analysis-binary search


Copyright Notice

  • This article original author: Columbia Valley's younger brother
  • Author blog address: http://blog.csdn.net/lfdfhl

Principle analysis

There is an ordered array {2, 5, 8, 12, 16, 23, 38, 56, 72, 91 }, please use the dichotomy to find the index corresponding to element 23.

Precondition

The premise of binary search is that the elements in the array are ordered, otherwise it cannot be searched.

Search principle

first step:

Determine the maximum, minimum, and middle subscripts of the entire array

The second step:

Compare the target value with the value corresponding to the maximum subscript, the value corresponding to the minimum subscript, and the value corresponding to the middle subscript

third step:

Adjust maximum subscript, minimum subscript, middle subscript

Find process

Insert picture description here

Code

The code implementation of binary search is as follows:

package com.algorithm;

/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 *
 */
public class BinarySearch {
    
    
	public static void main(String[] args) {
    
    
		int[] intArray = {
    
     2, 5, 8, 12, 16, 23, 38, 56, 72, 91 };
		int index = binarySearch(intArray, 23);
		System.out.println(index);
	}

	public static int binarySearch(int[] intArray, int value) {
    
    
		int max = intArray.length - 1;
		int min = 0;
		int mid = (max + min) / 2;
		while (intArray[mid] != value) {
    
    
			if (min <= max) {
    
    
				if (intArray[mid] > value) {
    
    
					max = mid - 1;
				} else if (intArray[mid] < value) {
    
    
					min = mid + 1;
				}
				mid = (max + min) / 2;
			} else {
    
    
				System.out.println("未查询到相应数据");
				mid = -1;
				break;
			}
		}
		return mid;
	}

}

operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/lfdfhl/article/details/109322224