Tuesday, 17 September 2013

What is wrong with my array insertion algorithm? (Java)

What is wrong with my array insertion algorithm? (Java)

NOTE you will need to know all the stuff I say up here before you
understand what I need help with
First, trust me I know there are better ways of doing this...including
methods that are already made for arrays. However my assignment requires
me to do it from scratch. Right now I am supposed to make a class that has
a final SIZE=100; and a next = 0; when the instance is created.
Since the array has 100 elements, and we don't want to print out the
entire thing, code as been written so that it only prints up to element
'next', an integer that tells us how many elements have been entered. So
at the beginning: next = 0 and whenever we insert an element, we are
supposed to increase next so that the correct number of elements are
printed in a client. All you need to know is that next must increase +1 by
the end of the method.
One last thing...you cannot use a separate array, and whenever an element
is added, it should be added such that all the elements from A[0] to
A[next] are in order (no sorting is allowed).
Here is what I have (it is inconsistent and doesn't work for some tests I
do):
public void insert(int n){
int left = 0;
int right = next;
while (left < right) {//Binary Search. Looks for where n should be
placed.
int middle = (left + right) / 2;
if(n < A[middle])
right = middle - 1;
else
left = middle + 1;
}
//Once the loop ends, left and right are equal, and the spot where
//n should go is found. We will name this index loc.
int loc = left; //or right, it doesn't matter since they are equal.
for(int i = next ; i-1 >= loc; i--) //Everything is copied one over
(right).
A[i] = A[i-1];
A[loc] = n; //The number is placed in the space that follows the
order.
next++; //Let the instance know that the size went up.
}

No comments:

Post a Comment