I need to create a method that inserts an integer into a sorted array of integers. I had already done this method but not with integers but with strings. Now I have a problem with integers.
My method with array of strings is:
public int inserisci(String s) throws IllegalStateException {
if(numElementi == elementi.length)
throw new IllegalStateException("Full array.");
int pos = ricercaBinaria(s);
if(pos > -1)
return -1;
if(elementi[-(pos + 1)] != null) {
for(int i = numElementi; i >= -(pos + 1); i--)
elementi[i + 1] = elementi[i];
}
elementi[-(pos + 1)] = s;
numElementi++;
return -(pos + 1);
}
For the array of strings I wrote this one:
public int insert(int x) throws IllegalStateException {
if(numElements == elements.length)
throw new IllegalStateException("Full array.");
int pos = binarySearch(x);
if(pos > -1)
return -1;
if(**elements[-(pos + 1)] != null**) {
for(int i = numElements; i >= -(pos + 1); i--)
elements[i + 1] = elements[i];
}
elements[-(pos + 1)] = x;
numElements++;
return -(pos + 1);
}
But the bold part (elements[-(pos + 1)] != null) is not correct. How can I replace it? Thanks
Integeror initialize the array with a value you know is outside the range you're going to use.