How to use recursion in creating a binary search algorithm

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

    Here is an easier way of doing binary search:

    public static int binarySearch(int intToSearch, int[] sortedArray) {
    
        int lower = 0;
        int upper = sortedArray.length - 1;
    
        while (lower <= upper) {
    
            int mid = lower + (upper - lower) / 2;
    
            if(intToSearch < sortedArray[mid]) 
    
                upper = mid - 1;
    
            else if (intToSearch > sortedArray[mid]) 
    
                lower = mid + 1;
    
            else 
    
                return mid;
        }
    
        return -1; // Returns -1 if no match is found
    }
    

提交回复
热议问题