Answer to Question #286062 in Java | JSP | JSF for Hamza

Question #286062

Task #12: Using Arrays and Methods


In this task, you are being asked to write methods that manipulate arrays in Java.


Write a method that swaps the value of the array in such a way that all negative values comes


before the positive values in the array. The method should then returns the array.


You may use the following header for this method:


static int[] negativeBeforePositive(int[] array)


NOTE: Declare and initialize the array without taking the input from user.


Treat the 0 as a value greater then negative numbers, but lesser than positive numbers.


You may declare some temporary arrays for your help.


1. Create a program called ArrayNegativeBeforePositiveLab1.java.


2. Create appropriate variables and assign values using a Scanner object.


3. Correctly display appropriate messages.

1
Expert's answer
2022-01-14T04:36:40-0500
import java.util.Arrays;

public class ArrayNegativeBeforePositiveLab1 {
    static int[] negativeBeforePositive(int[] array) {
        int[] result = new int[array.length];
        for (int i = 0, l = 0, r = array.length - 1; i < array.length; i++) {
            if (array[i] < 0) {
                result[l++] = array[i];
            } else if (array[i] > 0) {
                result[r--] = array[i];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] array = {5, 6, 0, 2, -3, 0, 5, 9, -8, -5, 2, 6, -4, 0};
        System.out.println(Arrays.toString(negativeBeforePositive(array)));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog