Fixing ArrayOutOfBound Error in BinarySearch

  • Context: Comp Sci 
  • Thread starter Thread starter pumas
  • Start date Start date
  • Tags Tags
    Error
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 3K views
pumas
Messages
15
Reaction score
0
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:
 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; 
           size++;
          }
          
         }

I appreciate any help :confused:
 
Physics news on Phys.org
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].
 
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