1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Arrays in Java

  1. Jun 26, 2007 #1
    I'm supposed to create a method that adds intergers to an array and keep it in sorted order. I'm supposed to search for the number in the array using binarySearch. I get an error that says arrayOutOfBound I don't know how to fix this. I have written the following code:
    elementData is the array,

    Code (Text):
     public void add(int value) {

          int index = binarySearch(elementData,value,0, size - 1);
          for (int i = size; i > index; i--)
               elementData[i] = elementData[i - 1];
               elementData[index] = value;
    I appreciate any help :confused:
  2. jcsd
  3. Jun 26, 2007 #2
    I'm a little rusty in my Java,
    so your algorithm there seems to move every value up in order to make a spot to place the new value in the right sorted order right?

    The only thing I can see is what happens when the new value is lower than all other values? so it goes all the way to i=0, and elementData[i-1] will give try to get to elementData[-1] which would be out of the boundary of the array.

    So maybe adding and if(i=0) will fix that? so you just replace the 0'th element, since it was already moved up to [1].
  4. Jun 26, 2007 #3
    Thanks for your help
  5. Jun 26, 2007 #4


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Well, if the array's length is called size, then the elements of that array range from 0 to size - 1. However, your for loop starts with i=size, meaning you're past the end of the array.

    - Warren
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook