DEV Community

Jeyaprasad R
Jeyaprasad R

Posted on

Move All Negative Elements to end

In this task, I worked on rearranging an array so that all positive numbers come first, followed by all negative numbers. This helped me understand how to separate elements based on a condition.

What I Did

I created a function called rearrange that takes an array containing both positive and negative numbers and rearranges it.

For example:
Input: [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]

How I Solved It

To solve this, I used two separate lists:

  • one to store positive numbers
  • one to store negative numbers

I went through each element in the array:

  • If the number is greater than or equal to 0, I added it to the positive list
  • If the number is negative, I added it to the negative list

After that, I combined both lists by placing positives first and negatives after.

Code

def rearrange(arr):
    pos = []
    neg = []
    for num in arr:
        if num >= 0:
            pos.append(num)
        else:
            neg.append(num)
    return pos + neg

print(rearrange([1, -1, 3, 2, -7, -5, 11, 6]))
print(rearrange([-5, 7, -3, -4, 9, 10, -1, 11]))
Enter fullscreen mode Exit fullscreen mode

How It Works

The function loops through the array only once and separates elements based on whether they are positive or negative. Then it joins both lists together to form the final rearranged array.

This approach is simple and makes the logic easy to understand.

Top comments (0)