DEV Community

Cover image for Move all negative elements to end
Abirami Prabhakar
Abirami Prabhakar

Posted on

Move all negative elements to end

so the question is to deal with the question that was given

Given an unsorted array arr[ ] having both negative and positive integers. The task is to place all negative elements at the end of the array without changing the order of positive elements and negative elements.

example question
Input : arr[] = [1, -1, 3, 2, -7, -5, 11, 6 ]
Output : [1, 3, 2, 11, 6, -1, -7, -5]

Appraoch

we are going to use 2 different lists to append the postive and negative elements seperately and concate them to together for the final output

given list

2 lists
-> postive
-> negative
in a for loop if
arr[i] >= 0
arr[i] is appended in postive list
else in the negative list

final = postive + negative

def rearrange(arr):
    pos = []
    neg = []

    for num in arr:
        if num >= 0:
            pos.append(num)
        else:
            neg.append(num)

    fn = pos + neg
    return fn
Enter fullscreen mode Exit fullscreen mode

Top comments (0)