Sort a binary array using one traversal

09 Jul, 2022
Given a binary array, sort it using one traversal and no extra space.Examples :  
Input : 1 0 0 1 0 1 0 1 1 1 1 1 1 0 0 1 1 0 1 0 0 
Output : 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
Explanation: The output is a sorted array of 0 and 1

Input : 1 0 1 0 1 0 1 0 
Output : 0 0 0 0 1 1 1 1
Explanation: The output is a sorted array of 0 and 1
 
Approach: This concept is related to partition of quick sort . In quick sort partition, after one scan, the left of the array is smallest and right of the array is the largest of selected pivot element.Algorithm:  
Create a variable index say j = -1Traverse the array from start to endIf the element is 0 then swap the current element with the element at index( jth ) position and increment the index (j) by 1.If the element is 1 keep the element as it is.
Create a variable index say j = -1
Traverse the array from start to end
If the element is 0 then swap the current element with the element at index( jth ) position and increment the index (j) by 1.
If the element is 1 keep the element as it is.
Implementation:  
CPP
Java
Python3
C#
PHP
Javascript
// CPP program to sort a binary array#include <iostream>using namespace std; void sortBinaryArray(int a[], int n){    int j = -1;    for (int i = 0; i < n; i++) {         // if number is smaller than 1        // then swap it with j-th number        if (a[i] < 1) {            j++;            swap(a[i], a[j]);        }    }} // Driver codeint main(){    int a[] = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1,                1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 };    int n = sizeof(a) / sizeof(a[0]);    sortBinaryArray(a, n);    for (int i = 0; i < n; i++)        cout << a[i] << " ";     return 0;}
// JAVA Code for Sort a binary// array using one traversalimport java.util.*; class GFG {     static void sortBinaryArray(int a[], int n)    {        int j = -1;        for (int i = 0; i < n; i++) {             // if number is smaller than 1            // then swap it with j-th number            if (a[i] < 1) {                j++;                int temp = a[j];                a[j] = a[i];                a[i] = temp;            }        }    }     /* Driver program to test above function */    public static void main(String[] args)    {         int a[] = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1,                    1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 };         int n = a.length;         sortBinaryArray(a, n);         for (int i = 0; i < n; i++)            System.out.print(a[i] + " ");    }}
# A Python program to sort a# binary arraydef sortBinaryArray(a, n):    j = -1    for i in range(n):         # if number is smaller        # than 1 then swap it        # with j-th number        if a[i] < 1:            j = j + 1                         # swap            a[i], a[j] = a[j], a[i]      # Driver programa = [1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1,        1, 1, 0, 0, 1, 1, 0, 1, 0, 0]n = len(a) sortBinaryArray(a, n) for i in range(n):        print(a[i], end = " ") # This code is contributed by Shrikant13.
// C# Code for Sort a binary// array using one traversalusing System; class GFG {     static void sortBinaryArray(int[] a,                                  int n)    {        int j = -1;        for (int i = 0; i < n; i++)        {             // if number is smaller than            // 1 then swap it with j-th            // number            if (a[i] < 1) {                j++;                int temp = a[j];                a[j] = a[i];                a[i] = temp;            }        }    }     /* Driver program to test above    function */    public static void Main()    {         int[] a = { 1, 0, 0, 1, 0, 1, 0,                    1, 1, 1, 1, 1, 1, 0,                    0, 1, 1, 0, 1, 0, 0 };         int n = a.Length;         sortBinaryArray(a, n);         for (int i = 0; i < n; i++)            Console.Write(a[i] + " ");    }} // This code is contributed by vt_m.
<?php// PHP Code for Sort a binary// array using one traversalfunction sortBinaryArray($a, $n){    $j = -1;    for ($i = 0; $i < $n; $i++)    {         // if number is smaller than        // 1 then swap it with j-th        // number        if ($a[$i] < 1)        {            $j++;            $temp = $a[$j];            $a[$j] = $a[$i];            $a[$i] = $temp;        }    }for ($i = 0; $i < $n; $i++)        echo $a[$i] . " ";     }  // Driver Code$a = array(1, 0, 0, 1, 0, 1, 0,           1, 1, 1, 1, 1, 1, 0,           0, 1, 1, 0, 1, 0, 0); $n = count($a);sortBinaryArray($a, $n); // This code is contributed by Sam007?>
<script>// Javascript Code for Sort a binary// array using one traversal     function sortBinaryArray(a, n)    {        let j = -1;        for (let i = 0; i < n; i++) {               // if number is smaller than 1            // then swap it with j-th number            if (a[i] < 1) {                j++;                let temp = a[j];                a[j] = a[i];                a[i] = temp;            }        }    }   // driver function        let a = [ 1, 0, 0, 1, 0, 1, 0, 1, 1, 1,                    1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 ];           let n = a.length;           sortBinaryArray(a, n);           for (let i = 0; i < n; i++)            document.write(a[i] + " ");     // This code is contributed by code_hunt.</script>   
Output :  
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
Complexity Analysis:  
Time Complexity: O(n). Only one traversal of the array is needed, So time Complexity is O(n).
 
Space Complexity:O(1). The space required is constant.
This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
shrikanth13
Sam007
andrew1234
code_hunt
navihere
binary-string
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexities of all Sorting Algorithms
Count Inversions in an array | Set 1 (Using Merge Sort)
Merge two sorted arrays
Radix Sort
Chocolate Distribution Problem
Find a triplet that sum to a given value
k largest(or smallest) elements in an array
Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
Minimum number of swaps required to sort an array
sort() in Python