DEV Community

Dharani
Dharani

Posted on

Move All Negative Elements To End

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:

  1. Create a new list for positive elements
  2. Create another list for negative elements
  3. Traverse the array and separate elements
  4. 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]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)