0

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.

0

1 Answer 1

0

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

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

Sign up to request clarification or add additional context in comments.

7 Comments

why not just with n instead of n-1 ?
Because, it is 0-based
So what????????
If array size is 3 then the indices are 0, 1, 2 (which is 3-1 = 2)
so no problem??
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.