Rearrange array in alternating positive & negative items
Input: arr[] = {1, 2, 3, -4, -1, 4}
Output : // Output: arr[] = {-4, 1, -1, 2, 3, 4}
Code
private static int[] reArrangeArray(Integer[] nums) { ArrayList<Integer> positive = new ArrayList<>(); ArrayList<Integer> negative = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[i] >= 0) { positive.add(nums[i]); } else { negative.add(nums[i]); } } int[] result = new int[nums.length]; int count=0 ; for (int i = 0; i < nums.length; i++) { count=i; if (negative.size() == 0 || positive.size() == 0) { break; } if (i % 2 == 0) { result[i] = positive.get(0); positive.remove(0); } else { result[i] = negative.get(0); negative.remove(0); } } if (negative.size() != 0) { while (negative.size() != 0) { result[count] = negative.get(0); negative.remove(0); count++; } } if (positive.size() != 0) { while (positive.size() != 0) { result[count] = positive.get(0); positive.remove(0); count++; } } return result; }