i need to add an item to my array in ascending order by using the compareTo method...
something is wrong with my boolean add method... something is not working good with my loops. can anyone help me please.
this is the code I have:
Code Java:
public boolean add(AnyType x)
{
if(theSize == items.length)
{
grow();
}
if(theSize == 0)
{
items[0] = x;
}
else if(contains(x) == false)
{
for(int i = 0; i < theSize; i++)
{
if(x.compareTo(items[i])>0)
{
int k = i+1;
while(k>0 && items[k-1].compareTo(x)<0)
{
items[k+2] = items[k+1];
items[k+1] = items[k];
k--;
}
items[k+1]=x;
break;
}
else if(x.compareTo(items[i])<0)
{
AnyType swap = items[i];
int k=i+1;
while(k>0 && items[k-1].compareTo(x)>0)
{
items[k+1] = items[k];
k=k-1;
}
items[k+1]=swap;
items[k] = x;
break;
}
}
}
theSize++;
return false;
}
Re: i need to add an item to my array in ascending order by using the compareTo metho
Quote:
Originally Posted by
twi
something is not working good
Please provide more information. What does "not working" mean? Do you get errors? Then copy and paste the EXACT error message. Do you get incorrect output? Then post your input, expected output and actual output.
One comment, why does the method always return false? I imagine it shoud return true if the new object was inserted successfully and false otherwise.
Re: i need to add an item to my array in ascending order by using the compareTo metho
every time i add an item if it contains in the array then boolean add is false and nothing happens like in the output number 2... every time i add a number it enters the item in the position it needs to be in in ascending order ... everything works out fine but when i insert 6 it wont shift all the way to the end... I dont know what is wrong with my code...
input: 5,5,0,3,6...
1) [5, null, null, null, null, null]
2) [5, null, null, null, null, null]
3) [0, 5, null, null, null, null]
4) [0, 3, 5, null, null, null]
5) [0, 6, 3, 5, null, null] (output expected after inserting 6 should be 0,3,5,6...)
Re: i need to add an item to my array in ascending order by using the compareTo metho
What I suggest you do instead of having all those ifs and loops inside the add method, refactor some of the code out to other methods. For example write a method that determines at what index the new value should be added. Write a method that moves all the values from x to theSize - 1 back a slot. If you do this then all your add method does is:
Code java:
else if(contains(x) == false) {
call method to find index to insert at
use above index to call method to move elements
insert new value at index
increase theSize
return true
}
return false
By the way in your if condition use the not operator and not == false.