What is wrong with this binary search? IndexOutOfBounds

463 Views Asked by At

I'm trying to write the binary search algorithm, But Geeks for Geeks practice problem Binary Search yields following error:

Runtime Error:
Runtime ErrorException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 

  Index 222 out of bounds for length 5

    at Solution.binarysearch(GFG.java:44)
    at GFG.main(GFG.java:22)

What I've written so far is,

class Solution {
    int binarysearch(int arr[], int n, int k){
        
        if (arr == null) return -1;
        
        int begin = 0;
        int end = k;

            for (; begin < end;)
            {
                int mid = (begin + end) / 2;
                if (arr[mid] == n) return mid;
                if (arr[mid] > n)
                {
                    // in left part
                    begin = begin;  // for debug
                    end = mid; 
                }
                else
                {
                    // in right part
                    begin = mid + 1;
                    end = end; // for debug
                }
            }

            return -1;
    }
}

Geeks for Geeks problem statement&example:

Given a sorted array of size N and an integer K, find the position at which K is present in the array using binary search.

Example 1:

Input: N = 5 arr[] = {1 2 3 4 5} K = 4
Output: 3
Explanation: 4 appears at index 3.

1

There are 1 best solutions below

7
On

Replace int end = k; to int end = n-1;

k is the number you have to find, n is the array size