Josiah Francis
Josiah Francis

Reputation: 17

java.lang.ArrayIndexOutOfBoundsException error when doing a binary search?

i am getting a little problem and i really do not know why. i am trying to program to search for a number input by the user using a binary searching method. it works well when the number in the middle of the array is searched for but when i attempt to search any other number am getting an error. here is my code.

import java.util.Scanner;

public class Main {

    public static void main(String args[])
    {
        //declaring array
        int array[] = {12,23,34,45,56,67,78,89};

        //declaring variables
        int search = 0;

        Scanner input = new Scanner(System.in);

        System.out.print("\n Enter: ");
        search = input.nextInt();


        binarySearch(array, search);
    }//end of main

    static public void binarySearch(int[] array, int search)
    {
        int begin = 0;
        int end = array.length-1;
        int mid = 0;
        boolean found = false;

        while(!found)
        {
            mid = (begin + end)/2;

            if(array[mid] == search)
            {
                found = true;
                search = array[mid];
            }
            else if(array[mid] < search)
            {
                begin = array[mid+1];
            }
            else if(array[mid] > search)
            {
                end = array[mid-1];
            }

        }//end of while loop

        //if(!found)
            //return ("BOOHOO your search was not found");

        System.out.print("Yippee i found "+ search + " at index " + mid);
    }

}//end of class

Upvotes: 0

Views: 303

Answers (1)

Pankaj Gadge
Pankaj Gadge

Reputation: 2814

When you don't find a search, you need to reset your begin and end pointers to the indexes and not on the values on those indexes i.e.

while(!found)
{
    mid = (begin + end)/2;

    if(array[mid] == search)
    {
        found = true;
    }
    else if(array[mid] < search)
    {
        begin = mid+1;
    }
    else if(array[mid] > search)
    {
        end = mid-1;
    }

}//end of while loop

Upvotes: 3

Related Questions