Answer to Question #288000 in Java | JSP | JSF for jeffy

Question #288000


1. Write a method that swaps the value of the array in such a way that all negative

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

return the array.

You may use the following header for this method:

public static int[] negativeBeforePositive(int[]

array)

For example, suppose that the array has 10 values: 25, 12, 0, -7, -4, 26, -2, 18, -

9, 11

The method will return an array which would contain the values: -7, -4, -2, -9, 25,

12, 0, 26, 18, 11

Write a method called printArray() which will take an integer array as input and

prints all its elements.

You may use the following header for this method:

public static void printArray(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.

Print the array before and after calling the negativeBeforePositive(int[] array)

method

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


1
Expert's answer
2022-01-16T17:51:39-0500
import java.util.Arrays;
import java.util.Scanner;

class Main {

    private static void printArray(int[] arr) {
        for (int j : arr) {
            System.out.print(j + " ");
        }

        System.out.println();
    }

    private static int[] negativeBeforePositive(int[] arr) {
        int[] resultArr = Arrays.copyOf(arr, arr.length);
        int key, j;

        for (int i = 1; i < resultArr.length; i++) {
            key = resultArr[i];

            if (key >= 0)
                continue;

            j = i - 1;
            while (j >= 0 && resultArr[j] >= 0) {
                resultArr[j + 1] = resultArr[j];
                j = j - 1;
            }

            resultArr[j + 1] = key;
        }

        return resultArr;
    }

    public static void main(String[] args) {
        // 1.
        int[] arr = {25, 12, 0, -7, -4, 26, -2, 18, -9, 11};
        printArray(arr);
        arr = negativeBeforePositive(arr);
        printArray(arr);

        //2.
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter size of array:");
        int[] arr2 = new int[scanner.nextInt()];

        for (int i = 0; i < arr2.length; i++) {
            System.out.printf("Enter value for %d index of array: ", i);
            arr2[i] = scanner.nextInt();
        }

        printArray(arr2);
        arr2 = negativeBeforePositive(arr2);
        printArray(arr2);
    }
}

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