This post will discuss a few problems that can be easily solved in linear time and constant space by modifying the partitioning logic of the Quicksort algorithm.

Problem #1

Given a binary array, sort it in linear time and constant space. The output should print all zeros, followed by all ones.

 
For example,

Input:  { 1, 0, 1, 0, 1, 0, 0, 1 }
Output: { 0, 0, 0, 0, 1, 1, 1, 1 }

 
The idea is to use 1 as a pivot element and make one pass of the partition process. The resultant array will be sorted. The following C++ program demonstrates it:

Download  Run Code

Output:

0 0 0 0 1 1 1 1

Problem #2

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 ]

 
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. This approach is demonstrated below in C++:

3

Download  Run Code

Output:

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

Problem #3

Given an integer array, rearrange it such that it contains positive and negative numbers at alternate positions. If the array contains more positive or negative elements, move them to the end of the array.

 
For example,

Input: { 9, -3, 5, -2, -8, -6, 1, 3 }
Output: { 5, -2, 9, -6, 1, -8, 3, -3 }

 
The idea is to use 0 as a pivot element and make one pass of the partition process. The resultant array will contain all positive integers to the end of the array and all negative integers at the beginning. Then swap alternate negative elements from the next available positive element until the end of the array is reached, or all negative or positive integers are exhausted.

Following is the C++ implementation of the idea:

Download  Run Code

Output:

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

Problem #4

Given an integer array, move all zeros present in it to the end. The solution should maintain the relative order of items in the array.

 
For example,

Input:  { 6, 0, 8, 2, 3, 0, 4, 0, 1 }
Output: { 6, 8, 2, 3, 4, 1, 0, 0, 0 }

 
The idea is to use 0 as a pivot element and make one pass of the partition process. The partitioning logic will read all elements, and each time we encounter a non-pivot element, swap it with the first occurrence of the pivot.

The implementation can be seen below in C++:

Download  Run Code

Output:

6 8 2 3 4 1 0 0 0