Algorithm Steps
- Given an array
arr
containing both positive and negative integers. - Create two separate lists: one for positive numbers and another for negative numbers while maintaining their order.
- Initialize a result array and use two pointers:
posIndex = 0
andnegIndex = 0
. - Start placing elements alternately: first positive, then negative (or vice versa depending on problem constraints).
- If one list is exhausted, append the remaining elements of the other list.
- Return the rearranged array.
Rearrange Array Alternating Positive and Negative Numbers Code
Python
JavaScript
Java
C++
C
def rearrange_alternating(arr):
pos = [x for x in arr if x >= 0]
neg = [x for x in arr if x < 0]
result = []
i = j = 0
while i < len(pos) and j < len(neg):
result.append(pos[i])
result.append(neg[j])
i += 1
j += 1
result.extend(pos[i:])
result.extend(neg[j:])
return result
# Sample Input
arr = [1, 2, 3, -4, -1, 4]
print("Rearranged Array:", rearrange_alternating(arr))