54.3k views
5 votes
Write a method named move Negatives(), that takes an array of integers as parameter. It returns a new array (do not modify the original data) that contains the exact same numbers as the given array, but arranged so that all the negative values are grouped at the start of the array in the order of the original array. The order of the positive numbers also must be the same as the original array.

1 Answer

2 votes

Final answer:

The moveNegatives() method rearranges an array of integers by separating negative numbers and grouping them at the start while preserving their original order, followed by positive numbers in their original order.

Step-by-step explanation:

Creating the moveNegatives() Method

To write the moveNegatives() method that rearranges an array of integers, we should create a new array and fill it with negative numbers first, followed by positive numbers, both in the same order they appear in the input array. The method should be written in a programming language (like Java or Python), and the steps generally involve iterating over the original array, detecting negative numbers, and storing them in the new array ahead of positive numbers.

Here's an example code outline in Java:

public int[] moveNegatives(int[] originalArray) {
int[] rearrangedArray = new int[originalArray.length];
int index = 0;
// First pass for negative numbers
for (int number : originalArray) {
if (number < 0) {
rearrangedArray[index++] = number;
}
}
// Second pass for positive numbers
for (int number : originalArray) {
if (number >= 0) {
rearrangedArray[index++] = number;
}
}
return rearrangedArray;
}

The method moveNegatives() first creates a new array called rearrangedArray with the same length as the original array. It uses two passes: the first adds all negative numbers to rearrangedArray, and the second adds all non-negative numbers. This ensures that the negative numbers are grouped at the beginning while preserving the order of negative and positive numbers from the original array.

User Jeanot Zubler
by
8.5k points