DEV Community

Jonah Blessy
Jonah Blessy

Posted on • Edited on

Move All Negative Elements to end

Problem Statement: here

PS Understanding:
An input array with a mix of positive and negative numbers are given. The task is to move all the negative numbers to the end of the array without changing the order of positive elements. The trick is to do this arrangement in-place and not use any temporary array.

Solution:

arr = [1, -1, 3, 2, -7, -5, 11, 6]
n = len(arr)
i = 0
while i < n:
    if arr[i] < 0:
        temp = arr[i]
        for j in range(i, n - 1):
            arr[j] = arr[j + 1]
        arr[n - 1] = temp
        n -= 1
    else:
        i += 1
print(arr)
Enter fullscreen mode Exit fullscreen mode
  • This was pretty easy and for reminded me of the "Odd or Even" problem I did during my initial days of coding.
  • Anyhow for this problem we initialize the values n= length of the array, i= first element of array.
  • If the element at arr[i] is negative, store it in a temporary variable, then move it to the end of the array. Decrease the value of n, since value at position n is already a negative number.
  • Else if the element at arr[i] is positive, move to the next element.

Top comments (0)