Move Negative
Elements To Front Of Array
Problem statement:
Move the negative elements of an array to the
front
Example:
Input will be:
2 -9 10 12 5 -2 10 -4
Output will be:
-9 -2 -4 2 10 12 5 10
Note:
The order of negative elements are same.
The order of positive elements are same.
All negative elements have been moved to
the front.
All positive elements have been moved to the
end or followed by all the negative elements.
Solving Strategy
Move Negative
Elements To Front Of Array
The idea of the algorithm is to have two pointers left
and right.
All the elements before left should be negative and all
elements after right should be positive. This way if any
elements are at their wrong positions swaps can occur
to correct it.
Steps:
1. Initialize left pointer to 0 and right pointer to
size(nums)-1
2. check if both left and right elements are negative,
increment left pointer if true
3. check if left element is positive and right element is
negative then swap the elements, increment left
and decrement right
4. check if both left and right elements are positive,
decrement right pointer if true
5. otherwise, increment left and decrement right
pointers
6. repeat 2-5 until left pointer <= right pointer