I believe code below can handle the task. I tested with a couple test cases and seemed to work. Please let me know in case it fails with any specific array.
Algorithm:
It locates the first positive and negative indices and stores them in pos and neg respectively.
Starts iterating from this point on by
Swaps the number at pos index with the number at neg index.
Stores the index ahead among pos and neg in a hash set swapped so that any index already swapped does not get swapped again.
Locates the next negative an positive indices for swapping.
Note that I implemented the algorithm in C# and let AI convert to to Java since I'm rusty with Java. Please let me know if anything seems odd with the Java code.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
int[] nums = { -1, 2, 3, -4, 5, 6, -7, -8, -9, 10 };
int pos = 0;
while (pos < nums.length && nums[pos] < 0)
++pos;
int neg = 0;
while (neg < nums.length && nums[neg] > 0)
++neg;
HashSet<Integer> swapped = new HashSet<>();
while (pos < nums.length && neg < nums.length) {
// swap
int temp = nums[pos];
nums[pos] = nums[neg];
nums[neg] = temp;
if (pos < neg)
swapped.add(neg);
else
swapped.add(pos);
do {
++pos;
} while (pos < nums.length && (swapped.contains(pos) || nums[pos] < 0));
do {
++neg;
} while (neg < nums.length && (swapped.contains(neg) || nums[neg] > 0));
}
for (int i = 0; i < nums.length; i++)
System.out.print(nums[i] + " ");
}
}