Comp Sci Fixing ArrayOutOfBound Error in BinarySearch

  • Thread starter Thread starter pumas
  • Start date Start date
  • Tags Tags
    Error
AI Thread Summary
The discussion focuses on fixing an ArrayOutOfBound error in a binary search implementation for adding integers to a sorted array. The error arises because the code attempts to access an index equal to the size of the array, which is out of bounds. A suggested solution is to adjust the for loop to start at size - 1 instead of size, ensuring it operates within valid index limits. Additionally, handling cases where the new value is lower than all existing values is crucial to avoid accessing negative indices. Properly managing the index and size will resolve the ArrayOutOfBound error.
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].
 
Thanks for your help
 
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
 

Similar threads

Replies
3
Views
1K
Replies
2
Views
2K
Replies
1
Views
1K
Replies
4
Views
1K
Replies
1
Views
1K
Replies
2
Views
1K
Replies
21
Views
3K
Back
Top