Sorting and Binary search using Java

前端 未结 4 677
离开以前
离开以前 2020-12-18 17:17

I was asked to sort and search an array. The sorting the array was simple and my code worked but then whenever I try to call the binary search method it works for the first

4条回答
  •  一个人的身影
    2020-12-18 17:33

    You goofed up the binary search intervals

    public static int rBsearch(int[] L, int low, int high, int k) {
    
    
        int mid = (low + high) / 2;
    
        if (low > high) {
            return -1;
        } else if (L[mid] == k) {
            return L[mid];
        } else if (L[mid] < k) {
            return rBsearch(L, mid + 1, high, k);
        } else {
            return rBsearch(L, low, mid - 1, k);
        }
     }
    

提交回复
热议问题