An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers.
Input : -12, 11, -13, -5, 6, -7, 5, -3, -6 Output :-12 -13 -5 -7 -3 -6 11 6 5
Note :- Order of elements is not important here.
The idea is to simply apply partition process of quicksort.
-1 -3 -7 4 5 6 2 8 9
Time complexity: O(n)
Auxiliary Space: O(1)
The problem becomes difficult if we need to maintain order of elements. Please refer Rearrange positive and negative numbers with constant extra space for details.
This article is contributed by Apoorva. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Rearrange positive and negative numbers with constant extra space
- Rearrange positive and negative numbers in O(n) time and O(1) extra space
- Move all negative elements to end in order with extra space allowed
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 2
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
- Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)
- Segregating negative and positive maintaining order and O(1) space
- Find ratio of zeroes, positive numbers and negative numbers in the Array
- C program to count Positive and Negative numbers in an Array
- Lambda expression in Python to rearrange positive and negative numbers
- Rearrange positive and negative numbers using inbuilt sort function
- Replace all elements by difference of sums of positive and negative numbers after that element
- Only integer with positive value in positive negative value in array
- Merge two sorted arrays in constant space using Min Heap
- Find duplicates in constant array with elements 0 to N-1 in O(1) space