0

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?

2
  • "Is this check true?" -- what do you mean by this? Are you talking about the java concept of boolean truth? In which case that value could be true if number == 5, array[4] == 4, , array[5] == 20. Commented Mar 22, 2014 at 23:16
  • can we assume that "true" means "right"? Commented Mar 22, 2014 at 23:36

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

0

I suggest you might make your question more clear (how to define "right position"?) There are at least 3 things to consider.

  1. Equal items. If you insert 19, your code will work incorrectly. If your origin array is 25 19 19 19 8 5 2, and another 19 is to be inserted, which position you define to be the right position?
  2. As your sequence is decreasing, so at least it should be like (number < array[i] && number >= array[i+1])
  3. When you insert 1 or 100, which should be inserted at the end or begin of the sequence, the code will work incorrectly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.