usersuper
usersuper

Reputation: 11

How to insert number in a sorted array

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

Answers (4)

Salix alba
Salix alba

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

Sentimental
Sentimental

Reputation: 187

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.

Upvotes: 0

Matthew Serrano
Matthew Serrano

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

tethernova
tethernova

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

Related Questions