Move All Negative Elements to End of Array
Problem Statement
Given an array of integers, move all negative elements to the end of the array while maintaining the order of positive elements.
Examples
Input
arr = [1, -1, 3, 2, -7, -5, 11, 6]
Output
[1, 3, 2, 11, 6, -1, -7, -5]
Input
arr = [-5, 7, -3, -4, 9, 10]
Output
[7, 9, 10, -5, -3, -4]
Approach 1 Using Extra Space
Create a new array to store positive and negative elements separately.
Steps
1 Traverse the array and store positive elements
2 Traverse again and store negative elements
3 Combine both
Code
```python id="neg1"
def moveNegatives(arr):
result = []
for num in arr:
if num >= 0:
result.append(num)
for num in arr:
if num < 0:
result.append(num)
return result
---
## Approach 2 In Place Method
Rearrange elements within the same array.
---
### Steps
1 Initialize index to track position
2 Traverse array
3 If element is positive swap it with current index
4 Increment index
---
### Code
```python id="neg2"
def moveNegatives(arr):
j = 0
for i in range(len(arr)):
if arr[i] >= 0:
arr[i], arr[j] = arr[j], arr[i]
j += 1
return arr
Explanation
The idea is to push all positive elements to the front and shift negative elements towards the end. The relative order of positive elements is maintained.
Expected Output
Input
arr = 1, -1, 3, 2, -7,
Top comments (0)