Given an array of positive and negative integers, segregate them in linear time and constant space. The output should print all negative numbers, followed by all positive numbers.

For example,

Input:  [9, -3, 5, -2, -8, -6, 1, 3]
Output: [-3, -2, -8, -6, 5, 9, 1, 3]

Practice this problem

We can solve this problem in linear time by using the partitioning logic of Quicksort. The idea is to use 0 as a pivot element and make one pass of the partition process. The resultant array will satisfy the given constraints. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

-3 -2 -8 -6 5 9 1 3

Java


Download  Run Code

Output:

[-3, -2, -8, -6, 5, 9, 1, 3]

Python


Download  Run Code

Output:

[-3, -2, -8, -6, 5, 9, 1, 3]

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.

 
The problem with this approach is that it changes the relative order of elements. The following solution uses the merge sort algorithm and maintains the relative order of elements.

Segregate positive and negative integers using merge sort

 
Exercise: Modify the solution so that positive integers will come first.