How to use recursion in creating a binary search algorithm

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

    Here is a algorithm which should get you going. Let your method signature be:

    public boolean binarysearchRecursion(Array, begin_index,end_index, search_element)
    
    1. Check if your begin_index > end_index if YES then return false.
    2. Calculate mid_element for your input array.
    3. Check if your search_element is equal to this mid_element. if YES return true
    4. If mid_element > search_element Call your method with for range 0 - mid
    5. If mid_element < search_element Call your method with for range mid+1 - Length_of_Array

    Also as @DwB said in his comment you are better using loop to get things done. Some problems are recursive in nature(Like binary tree problems). But this one is not one of them.

    0 讨论(0)
  • 2020-12-05 22:00

    This is another way of doing recursion:

    int[] n = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    @Test
    public void testRecursiveSolution() {
        Assert.assertEquals(0, recursiveBinarySearch(1,n));
        Assert.assertEquals(15, recursiveBinarySearch(16,n));
        Assert.assertEquals(14, recursiveBinarySearch(15,n));
        Assert.assertEquals(13, recursiveBinarySearch(14,n));
        Assert.assertEquals(12, recursiveBinarySearch(13,n));
        Assert.assertEquals(11, recursiveBinarySearch(12,n));
        Assert.assertEquals(10, recursiveBinarySearch(11,n));
        Assert.assertEquals(9, recursiveBinarySearch(10,n));
        Assert.assertEquals(-1, recursiveBinarySearch(100,n));
    }
    private int recursiveBinarySearch(int n, int[] array) {
        if(array.length==1) {
            if(array[0]==n) {
                return 0;
            } else {
                return -1;
            }
        } else {
            int mid = (array.length-1)/2;
            if(array[mid]==n) {
                return mid;
            } else if(array[mid]>n) {
                return recursiveBinarySearch(n, Arrays.copyOfRange(array, 0, mid));
            } else {
                int returnIndex = recursiveBinarySearch(n, Arrays.copyOfRange(array, mid+1, array.length));
                if(returnIndex>=0) {
                    return returnIndex+mid+1;
                } else {
                    return returnIndex;
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题