Home > Java > javaTutorial > Java binary search implementation principle and code implementation

Java binary search implementation principle and code implementation

王林
Release: 2023-04-27 08:52:06
forward
1110 people have browsed it

1. Description of binary search steps

(1) First determine the middle position of the entire search interval mid = (left right)/2

(2) Use The keyword value to be searched is compared with the keyword value in the middle position;

If they are equal, the search is successful

If it is greater, continue the search in half in the last (right) half area

If it is less than, continue the half search in the front (left) half area

(3) Press the half formula again for the determined reduced area, and repeat the above steps.

Finally, the result is obtained: either the search is successful or the search fails. The storage structure of binary search is stored in a one-dimensional array. Example of half search algorithm

Java binary search implementation principle and code implementation2. Requirements

(1) A sequential storage structure must be used.

(2) Must be arranged in order by keyword size.

3. Example

public class Demo {
 
    public static void main(String[] args) {
        int[] arr={-1,0,3,5,9,12};//查找的数组
        int searchNum=13;//查找的目标数
        Arrays.sort(arr);
 
        int resultOne=binarySearchOne(arr,searchNum,0,arr.length-1);
        System.out.println(resultOne);
 
        int resultTwo=binarySearchTwo(arr,searchNum);
        System.out.println(resultTwo);
    }
 
    /**
     * 递归实现
     * @param arr
     * @param searchNum
     * @param start
     * @param end
     * @return
     */
    public static int binarySearchOne(int[] arr,int searchNum,int start,int end){
        if(start>end)
            return -1;
        int middle=(start+end)/2;
        if(searchNum<arr>arr[middle])
            return binarySearchOne(arr,searchNum,middle+1,end);
        else
            return middle;
    }
 
    /**
     * 非递归实现
     * @param arr
     * @param searchNum
     * @return
     */
    private static int binarySearchTwo(int[] arr, int searchNum) {
        int start=0;
        int end=arr.length-1;
        while(startarr[middle])
                start=middle+1;
            else
                return middle;
        }
        return -1;
    }
}</arr>
Copy after login

The above is the detailed content of Java binary search implementation principle and code implementation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template