# Separate 0’s and 1’s in a given array

Objec­tive:  Given an array which contains only 0’s and 1’s. write an algorithm to separate 0’s and 1’s.

Example

```int [] arrA = {1,0,1,0,1,1,0,0,0,0,1};
Output: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]```

Approach: Counting

• Count number of 0’s in the array. Say its count.
• Now in array, put 0 in indexes from 0 to count – 1.
• In rest of the array put 1.

Time Complexity: O(n)

Code:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

 import java.util.Arrays; public class Separate0and1Counting { public static int[] arrange(int [] arrA){ //count number of 0's int countOs=0; int size = arrA.length; for (int i = 0; i 0) { arrA[i] = 0; countOs—; } else arrA[i]=1; } return arrA; } public static void main(String[] args) { int [] arrA = {1,0,1,0,1,1,0,0,0,0,1}; System.out.println("Rearranging arrays using counting.."); arrA = arrange(arrA); System.out.println(Arrays.toString(arrA)); } }

Output: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

Approach: Swapping Indexes

• Use two indexes, left and right.
• Put left index at the start of array and right at the end of the array.
• Swap left and right elements
• Do it till left<right

Time Complexity: O(n)

Code:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
`[0, 0, 0, 1, 1, 1, 1, 1]`