![]() |
VOOZH | about |
Given an unsorted array arr[ ] having both negative and positive integers. Place all negative elements at the end of the array without changing the order of positive elements and negative elements.
Examples:
Input: arr[] = [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]
Explanation: All negative elements [-1, -7, -5] were arranged after positive elements [1, 3, 2, 11, 6] and the relative ordering was also preserved.Input: arr[] = [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]
Explanation: All negative elements [-5, -3, -4, -1] were arranged after positive elements [7, 9, 10, 11] and the relative ordering was also preserved.
The idea is to use a temporary array that first stores positives and then negatives. Finally copy temp back to arr.
For example, arr[] = [1, -1, -3, -2, 7, 5, 11, 6]
1 7 5 11 6 -1 -3 -2
Related Articles:
Rearrange positive and negative numbers with constant extra space
Alternate Rearrangement of Positives and Negatives