DEV Community

Luckshvadhan B
Luckshvadhan B

Posted on

Move All Negative Elements to End

Approach:
Step 1 Take the array
Step 2 Create temp array
Step 3 Add all positive elements first
Step 4 Then add all negative elements
Step 5 Copy back to original array

Why this works???
We maintain order
first loop keeps positives in same order
second loop keeps negatives in same order
so no disturbance

Code
def rearrange(arr):
temp=[]
for x in arr:
if x>=0:
temp.append(x)
for x in arr:
if x<0:
temp.append(x)
for i in range(len(arr)):
arr[i]=temp[i]

Limitation:
Uses extra space and
not fully in place
but safest approach

Top comments (0)