I want to produce the code which will do the following for me:
- insert an element into array
- find the position of the element in the array
For some reason (I think this might be because of the insertionSort method), I am not getting the desired results. If I, for example, insert 4 elements to the array with a length 5 the last element inserted should be at index 3. However, at the moment the position that I got is 4, which is wrong.
My question is what I have to use to make this code works as it should, when I am trying to use Integer instead of int (to check if there is null at next position to stop the insertionSort from executing) I am getting a NullPointerException (I replace all int[] to Integer[] without changing anything else).
public class arrayImplementation implements programInterface
{
int pointer = 0;
int number = -1;
static int[] theArray;
public arrayImplementation(int size) {
theArray = new int[size];
}
@Override
public void insert(int key) {
theArray[pointer] = key;
if(pointer != 0){
insertionSort(theArray);
}
pointer++;
}
@Override
public int find(int key) {
int low = 0;
int high = theArray.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (theArray[mid] == key) {
number = mid;
return number;
}
if (theArray[mid] < key) {
low = mid + 1;
}
if (theArray[mid] > key) {
high = mid - 1;
}
}
return number;
}
@Override
public void delete(int key) {}
public void insertionSort(int[] theArray) {
for (int i = 1; i < theArray.length; i++) {
int temp = theArray[i];
int j = i;
while (j > 0 && temp < theArray[j - 1]) {
theArray[j] = theArray[j - 1];
j = j - 1;
}
theArray[j] = temp;
}
}
public static void main(String arg[]) {
arrayImplementation arrImp = new arrayImplementation(5);
arrImp.insert(1);
arrImp.insert(2);
arrImp.insert(3);
arrImp.insert(7);
System.out.println(arrImp.find(7));
for(int i = 0;i<theArray.length;i++){
System.out.println(theArray[i]+", ");
}
}
}
theArraystatic? That's going to cause you some problems as soon as you have more than one instance of your class.arrImp.theArrayso that it doesn't need to be static.