Home > Java > javaTutorial > How to use recursion in Java's binary search algorithm?

How to use recursion in Java's binary search algorithm?

WBOY
Release: 2023-05-09 18:40:08
forward
885 people have browsed it

1. Recursive concept

The programming technique in which a program calls itself is called recursion. Turn large-scale problems into small-scale problems. The problem remains the same and the scale becomes smaller.

2. Two prerequisites

Termination condition - when certain conditions are met, the function returns a specific value and no longer calls recursively

Recursive call ——The function calls itself, and its input value is closer to the termination condition

3. Recursive example of binary search

/**
     * 递归实现二分查找
     * @param arr
     * @param left
     * @param right
     * @param val
     * @return
     */
private static int binarySearch(int[] arr, int left, int right, int val) {
        if (val < arr[left] || val > arr[right] || left > right) {
            return -1;
        }
        int middle = (left + right)/2;
        if(val < arr[middle]){
            return binarySearch (arr,0,middle-1,val);
        }
        if(val > arr[middle]){
            return binarySearch (arr,middle+1,right,val);
        }else{
            return middle;
        }
}
Copy after login

The above is the detailed content of How to use recursion in Java's binary search algorithm?. 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