How to use recursion in creating a binary search algorithm

后端 未结 8 2302
孤城傲影
孤城傲影 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-05 21:35

    While it doesn't return the index, this at least returns the idea of 'yes' or 'no' that something is in the collection:

    public static boolean recursive(int[] input, int valueToFind) {
        if (input.length == 0) {
            return false;
        }
    
        int mid = input.length / 2;
        if (input[mid] == valueToFind) {
            return true;
        } else if (input[mid] > valueToFind) {
            int[] smallerInput = Arrays.copyOfRange(input, 0, mid);
            return recursive(smallerInput, valueToFind);
        } else if (input[mid] < valueToFind) {
            int[] smallerInput = Arrays.copyOfRange(input, mid+1, input.length);
            return recursive(smallerInput, valueToFind);
        }
    
        return false;
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 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<a[middle]) {
            return binarySearch(a, start, middle - 1, target);
        } else {
            return binarySearch(a, middle + 1, end, target);
        }
    }
    
    0 讨论(0)
  • 2020-12-05 21:53

    A possible example is :

    // need extra "helper" method, feed in params
       public int binarySearch(int[] a, int x) { 
          return binarySearch(a, x, 0, a.length - 1);
       }
    
       // need extra low and high parameters
       private int binarySearch(int[ ] a, int x,
             int low, int high) {
          if (low > high) return -1; 
          int mid = (low + high)/2;
          if (a[mid] == x) return mid;
          else if (a[mid] < x)
             return binarySearch(a, x, mid+1, high);
          else // last possibility: a[mid] > x
             return binarySearch(a, x, low, mid-1);
       }
    

    Here you can check in C Binary Search, With and Without Recursion

    Source : http://www.cs.utsa.edu/~wagner/CS3343/recursion/binsearch.html

    0 讨论(0)
  • 2020-12-05 21:55

    Following is a code sample extracted from here.

    public class BinarySearch {
    
        public boolean find(int[] sortedValues, int value) {
            return search(sortedValues, value, 0, sortedValues.length - 1);
        }
    
        private boolean search(int[] sorted, int value, int leftIndex, int rightIndex) {
    
            // 1. index check
            if (leftIndex > rightIndex) {
                return false;
            }
    
            // 2. middle index
            int middle = (rightIndex + leftIndex) / 2;
    
            // 3. recursive invoke
            if (sorted[middle] > value) {
                return search(sorted, value, leftIndex, middle - 1);
            } else if (sorted[middle] < value) {
                return search(sorted, value, middle + 1, rightIndex);
            } else {
                return true;
            }
        }
    }
    

    You can find implementations of the below test cases against the above binary search implementation as well in the reference link.

    1. shouldReturnFalseIfArrayIsEmpty()
    2. shouldReturnFalseIfNotFoundInSortedOddArray()
    3. shouldReturnFalseIfNotFoundInSortedEvenArray()
    4. shouldReturnTrueIfFoundAsFirstInSortedArray()
    5. shouldReturnTrueIfFoundAtEndInSortedArray()
    6. shouldReturnTrueIfFoundInMiddleInSortedArray()
    7. shouldReturnTrueIfFoundAnywhereInSortedArray()
    8. shouldReturnFalseIfNotFoundInSortedArray()
    
    0 讨论(0)
提交回复
热议问题