In: Computer Science
Given an array of integers, implement (in Java) the moveAllNegativeOne method to
move all -1 present in the array to the end. The algorithm should maintain the relative
order of items in the array and worst-case running time complexity must be linear.
Example:
Input: [6, -1, 8, 2, 3, -1, 4, -1, 1]
Output: [6, 8, 2, 3, 4, 1, -1, -1, -1]
Important Notes:
• You must add the main method in your program in Java in order to test your
implementation.
• You can use the array of the previous example to test your program, however, I
suggest that you also use other input arrays to validate the correctness and
efficiency of your solution.
• Your program MUST be submitted only in source code form (.java file).
• A program that does not compile or does not run loses all correctness points.
public class Main {
public static void moveAllNegativeOne(int arr[]) {
int nonMinusOnes = 0;
for (int i = 0; i < arr.length; i++)
if (arr[i] != -1)
arr[nonMinusOnes++] = arr[i];
while (nonMinusOnes < arr.length)
arr[nonMinusOnes++] = -1;
}
public static void main(String[] args) {
int arr[] = new int[]{6, -1, 8, 2, 3, -1, 4, -1, 1};
moveAllNegativeOne(arr);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " " );
}
}
====================================
SEE OUTPUT

========================================
Thanks, let me now if there is any concern.