Reputation: 11
I have an array with numbers like this:
25, 19, 14, 11, 9, 7, 5, 2
and I want to insert a number at the right position
I wrote this but I don't know if the code is true. Can you help me?
if(number > array[i] && number < array[i+1]){
rightposition = i;
}
Is this check true?
Upvotes: 0
Views: 161
Reputation: 7824
Use TreeSet<Integer>
this is a sorted list.
Set<Integer> list = new TreeSet<Integer>();
list.addAll(array); // add all the data
The sorting happens automatically as you insert the elments, using a Set will remove duplicate elements.
Upvotes: 1
Reputation: 187
I suggest you might make your question more clear (how to define "right position"?) There are at least 3 things to consider.
Upvotes: 0
Reputation: 503
I'm assuming this portion of code is executing inside a for loop (you may want to post more of your code to ensure we're making the right assumptions).
This code will fail with a NullPointerException if the current element is the last element in the array.
Upvotes: 0
Reputation: 135
What you are saying makes logical sense, but I don't know if it's correct because I don't know what "right position" means for your code. If you could post more of your code, it might be easier to answer your question.
Upvotes: 0