Segregate 0s and 1s in an Array – Java Code

How to Segregate 0s and 1s in an Array.

Given an array of 0s and 1s in a random order. We have to write a code to segregate 0s on the left side and 1s on the right side of the array.

Basically, we have to sort an array of 0s and 1s.

For example –

Input array   =  [0, 1, 0, 1, 0, 0, 1]
Output array = [0, 0, 0, 0, 1, 1, 1]

In an input array 0s and 1s are in an unsorted order. The output is the sorted order of 0s and 1s.

How to sort an array of 0 and 1 in one traversal

How to sort an array of 0s and 1s in a Single traversal

This programming problem is similar to the problem of move all zeroes to end of array.  In this tutorial, I am going to discuss multiple approaches and it’s java code to solve this problem.

Sort an array of 0s, 1s and 2s.

Let’s start with the easiest approach first. What’s the easiest approach we can use to solve this problem. The simplest approach is to sort an array of 0s and 1s. Once the array is sorted all zeroes moves on the left side and 1s on the right side.

The time complexity of sorting an array is O(nlogn).

How we can improve our solution to solve this problem in O(n) time complexity?

Algorithm to Segregate 0s and 1s in an Array in Single Traversal

To solve this problem in a single traversal. Traverse an array and put the 0s at the beginning. Once we put all the zeroes at the beginning of an array we are only left with 1s. Then put 1s in an array.

The time complexity of this approach is O(n) and it’s space complexity is O(1).

Programming video tutorials

Segregate 0s and 1s in an Array – Java Code

In this coding example,  Let’s implement the algorithm which we discussed above.

In this video tutorial, I have explained how to sort an array of 0s and 1s in a single traversal.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.