![]() |
VOOZH | about |
Given an array containing both positive and negative numbers in random order. The task is to rearrange the array elements so that all negative numbers appear before all positive numbers.
Note:
Example :
Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
Output: -12 -13 -5 -7 -3 -6 11 6 5
The idea is to sort the array of elements, this will make sure that all the negative elements will come before all the positive elements.
Below is the implementation of the above approach:
-13 -12 -7 -6 -5 -3 5 6 11
Time Complexity: O(n*log(n)), Where n is the length of the given array.
Auxiliary Space: O(1)
The idea is to apply the partition process of quicksort. Initialize a variable (lets say j) to 0, and then traverse the array. If a negative number is encountered, then simply swap the current value and value at j, and increment the value of j.
-12 -13 -5 -7 -3 -6 5 6 11
Time complexity: O(n)
Auxiliary Space: O(1)
The idea is to solve this problem with constant space and linear time is by using a two-pointer.
Step by step approach:
Below is the implementation of the above approach:
-12 -6 -13 -5 -3 -7 5 6 11
Time Complexity: O(n)
Auxiliary Space: O(1)
The idea is to traverse the array to find the number of negative numbers in the array. Then traverse the array again, and move the negative numbers to their respective indices.
-12 -13 -5 -7 -3 -6 5 6 11
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Article: