How to use recursion in creating a binary search algorithm

后端 未结 8 2340
孤城傲影
孤城傲影 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:34

    A recursion BinarySearch with break conditions in case you can not find the value you are looking for

    public interface Searcher{
        public int search(int [] data, int target, int low, int high);
    }
    

    The Implementation

    public class BinarySearch implements Searcher {
    
        public int search(int[] data, int target, int low, int high) {
            //The return variable
            int retorno = -1;
            if(low > high) return retorno;
            int middle = (high + low)/2;
            if(target == data[middle]){
                retorno = data[middle];
            }else if(target < data[middle] && (middle - 1 != high)){
                //the (middle - 1 != high) avoids beeing locked inside a never ending recursion loop
                retorno = search(data, target, low, middle - 1);
            }else if(target > data[middle] && (middle - 1 != low)){
                //the (middle - 1 != low) avoids beeing locked inside a never ending recursion loop
                retorno = search(data, target, middle - 1, high);
            }else if(middle - 1 == low || middle - 1 == high){
                //Break condition if you can not find the desired balue
                retorno =  -1;
            }
            return retorno;
        }
    }
    

提交回复
热议问题