Binary Array Sorting
Posted: 25 Dec, 2020
Difficulty: Easy
A binary array is an array consisting of only 0s and 1s.
You are given a binary array "arr" of size ‘N’. Your task is to sort the given array and return this array after sorting.
Input Format :
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘2*T’ lines represent the ‘T’ test cases.
The first line of each test case contains an integer ‘N' denoting the size of the array.
The second line of each test case contains ‘N’ space-separated integers consisting of 0s and 1s as the array elements.
Output Format :
For each test case, print ‘N’ space-separated integers representing the elements of the sorted binary array in a separate line.
Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Follow Up :
1. Can you solve this problem in a linear time and constant space?
2. Can you solve this problem in a single traversal only?
Constraints :
1 <= T <= 50
1 <= N <= 10^4
0 <= arr[i] <= 1
Where ‘T’ is the number of test cases and ‘N’ is the size of the array.
Time Limit: 1 sec
Approach 1
- Initialize an integer variable ‘countZero’:= 0, It will store the count of zeros in the given array.
- Iterate over the given array, if the current element is 0 then increment ‘countZero’ by 1.
- Run a loop where ‘i’ ranges from ‘0’ to ‘n-1’. If ‘i’ < ‘countZero’ then place 0 at that index in the given array, otherwise place 1.
- Return this array.
Note -: Instead of counting 0 we can also count 1 in the given array and similarly solve this problem.
Approach 2
This problem can be solved in a single traversal also. The concept used for this approach is related to the partition of quicksort. In a quick sort’ partition, after one scan, the left of the array is the smallest and the right of the array is the largest of the selected pivot element. Here we don't make any pivot but we make the smaller(0) come back in the array and Larger value(1) go ahead in the array.
- Create an integer variable ‘index’ = 0.
- Traverse the array from start to end and do the following -
- If the element is 0, then swap the current element with the element at ‘index’ position. and increment the ‘index’ by 1.
- If the element is 1 keep the element as it is.
- Return this array.
SIMILAR PROBLEMS
Min Heap
Posted: 5 May, 2022
Difficulty: Moderate
Left Rotate an Array by One
Posted: 17 May, 2022
Difficulty: Easy
Largest Element in the Array
Posted: 17 May, 2022
Difficulty: Easy
Matrix Boundary Traversal
Posted: 20 May, 2022
Difficulty: Easy
Even Odd Pulse
Posted: 9 Jun, 2022
Difficulty: Moderate