How to use recursion in creating a binary search algorithm

后端 未结 8 2371
孤城傲影
孤城傲影 2020-12-05 21:19

I have been using my time off university to practice Java through coding algorithms. One of the algorithms I coded was the binary search:

public class Binary         


        
8条回答
  •  忘掉有多难
    2020-12-05 21:41

    If you really want to use recursion, this should do it.

    public static int binarySearch(int[] a, int target) {
        return binarySearch(a, 0, a.length-1, target);
    }
    
    public static int binarySearch(int[] a, int start, int end, int target) {
        int middle = (start + end) / 2;
        if(end < start) {
            return -1;
        } 
    
        if(target==a[middle]) {
            return middle;
        } else if(target

提交回复
热议问题