Introduction
Rearranging elements in an array is a common problem in programming. One such problem is moving all negative elements to the end while maintaining the order of positive elements.
Problem Statement
Given an array of integers, move all negative elements to the end of the array while keeping the order of positive elements unchanged.
Approach
We can solve this problem using a simple method:
- Create a new list for positive elements
- Create another list for negative elements
- Traverse the array and separate elements
- Combine positive elements followed by negative elements
Python Code (Using Extra Space)
python
def move_negatives(arr):
positives = []
negatives = []
for num in arr:
if num >= 0:
positives.append(num)
else:
negatives.append(num)
return positives + negatives
# Example
arr = [1, -2, 3, -4, 5, -6]
print("Result:", move_negatives(arr))
## Input
[1, -2, 3, -4, 5, -6]
## output
[1, 3, 5, -2, -4, -6]
Top comments (0)