#Need help with Java. The method is supposed to modify an array of positive and negative integers.

1 messages · Page 1 of 1 (latest)

fading scaffold
#

For example let say you have an array of {-1,2,-3, 4,- 5, 6, 7} it supposed to return {-1,-3,-5,2,6,7}

public static int[] moveNegatives(int[] value){
        int[] newValues = new int[value.length];
        int negative = 0;
        int positive = 0;
        for (int i = 0; i < value.length; i++){
            // checking for a negative number
            if (value[i] < 0){
                newValues[negative] = value[i];
                negative++;
            }
            // if the values is not negative
            else{
                newValues[positive + 1] = value[i];
                positive += 1;
            }
        }
eternal mango
#

newValues[positive + 1] = value[i];

you might go out of bound here

#

you are not doing bound checking

#

also why is negative and positive if/else different ?

#

value[i] should be extracted as v

#

and value.length should be extracted as n

#

both final

#

always use pre-increment also

#
public static final int[] moveNegatives(final int[] value)
{
        final int n = value.length
        int[] newValues = new int[n];
        int negative = 0;
        int positive = 0;
        for (int i = 0; i < n; ++i)
        {
            final int v = value[i];
            // checking for a negative number
            if (v < 0) {
                newValues[negative] = v;
                ++negative;
            }
            // if the values is not negative
            else {
                newValues[positive] = v;
                ++positive;
            }
        }
 return newValues;
}
#

also your logic is wrong, because negative = positive = 0 will override each other

#
public static final int[] moveNegatives(final int[] value)
{
        final int n = value.length
        final int[] negativeValues = new int[n];
        final int[] positiveValues = new int[n];
        int negative = 0;
        int positive = 0;
        for (int i = 0; i < n; ++i) {
            final int v = value[i];
            // checking for a negative number
            if (v < 0) {
                negativeValues[negative] = v;
                ++negative;
            }
            // if the values is not negative
            else {
                positiveValues[positive] = v;
                ++positive;
            }
        }

  // Pad the positive after negatives shift
  for (int i = 0; i < positive; ++i)
  {
     negativeValues[negative + i] = positiveValues[i];
  }

  return negativeValues;
}