Sort a binary array using one traversal and no extra space (original) (raw)

Last Updated : 26 Apr, 2024

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

Sort a binary array using one traversal using partition function of quicksort:

This concept is related to partition of quick sort . In the quick sort partition function, 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

Follow the given steps to solve the problem:

Below is the implementation of the above approach:

CPP `

// CPP program to sort a binary array #include 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 code int 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]);

// Function call
sortBinaryArray(a, n);
for (int i = 0; i < n; i++)
    cout << a[i] << " ";

return 0;

}

Java

// JAVA Code for Sort a binary // array using one traversal import 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 code
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;

    // Function call
    sortBinaryArray(a, n);

    for (int i = 0; i < n; i++)
        System.out.print(a[i] + " ");
}

}

Python3

A Python program to sort a

binary array

def 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 code

if name == "main": a = [1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0] n = len(a)

# Function call
sortBinaryArray(a, n)

for i in range(n):
    print(a[i], end=" ")

This code is contributed by Shrikant13.

C#

// C# Code for Sort a binary // array using one traversal using 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 code
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;

    // Function call
    sortBinaryArray(a, n);

    for (int i = 0; i < n; i++)
        Console.Write(a[i] + " ");
}

}

// This code is contributed by vt_m.

JavaScript

// 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++)
       console.log(a[i] + " ");

// This code is contributed by code_hunt.

PHP

i<i < i<n; $i++) { // if number is smaller than // 1 then swap it with j-th // number if ($a[$i] < 1) { $j++; temp=temp = temp=a[$j]; a[a[a[j] = a[a[a[i]; a[a[a[i] = $temp; } } for ($i = 0; i<i < i<n; $i++) echo a[a[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(n = count(n=count(a); // Function call sortBinaryArray($a, $n); // This code is contributed by Sam007 ?>

`

Output

0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1

**Time Complexity: O(N), Only one traversal of the array is needed, So the time Complexity is O(N)
**Auxiliary Space: O(1). The space required is constant

**Sort a binary array using one traversal and no extra space using **Two Pointer

Step-by-step approach:

Below is the implementation of the above Approach:

C++ `

#include #include

void solve(std::vector& arr, int n) { // Initialize two pointers, one at the beginning and one at the end of the array. int i = 0; int j = n - 1;

// Iterate until the two pointers meet.
while (i < j) {
    // If the element at the current index is 1 and the element at the end of the array is 0,
    // swap the two elements.
    if (arr[i] == 1 && arr[j] == 0) {
        std::swap(arr[i], arr[j]);

        // Move the left pointer one position to the right.
        i++;

        // Move the right pointer one position to the left.
        j--;
    }

    // If the element at the current index is 0, move the left pointer one position to the right.
    else if (arr[i] == 0) {
        i++;
    }

    // If the element at the end of the array is 1, move the right pointer one position to the left.
    else if (arr[j] == 1) {
        j--;
    }
}

}

int main() { // Example usage std::vector arr = {0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1}; int n = arr.size(); solve(arr, n);

// Output the modified array
for (int num : arr) {
    std::cout << num << " ";
}
std::cout << std::endl;  // Output: 0 0 0 0 0 1 1 1 1 1 1

return 0;

}

Java

import java.io.*;

class GFG { public static void Solve(int A[], int n) {

    // Initialize two pointers, one at the beginning and
    // one at the end of the array.
    int i = 0;
    int j = n - 1;

    // Iterate until the two pointers meet.
    while (i < j) {

        // If the element at the current index is 1 and
        // the element at the end of the array is 0,
        // swap the two elements.
        if (A[i] == 1 && A[j] == 0) {
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;

            // Move the left pointer one position to the
            // right.
            i++;

            // Move the right pointer one position to
            // the left.
            j--;
        }

        // If the element at the current index is 0,
        // move the left pointer one position to the
        // right.
        else if (A[i] == 0) {
            i++;
        }

        // If the element at the end of the array is 1,
        // move the right pointer one position to the
        // left.
        else if (A[j] == 1) {
            j--;
        }
    }
}

public static void main(String[] args)
{
    // Create an array of 0s and 1s.
    int arr[] = { 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1 };

    // Sort the array using the Solve() method.
    Solve(arr, arr.length);

    // Print the sorted array.
    for (int i : arr) {
        System.out.print(i + " ");
    }
}

}

Python3

def solve(arr, n):

# Initialize two pointers, one at the beginning and one at the end of the array.
i = 0
j = n - 1

# Iterate until the two pointers meet.
while i < j:

    # If the element at the current index is 1 and the element at the end of the array is 0,
    # swap the two elements.
    if arr[i] == 1 and arr[j] == 0:
        arr[i], arr[j] = arr[j], arr[i]

        # Move the left pointer one position to the right.
        i += 1

        # Move the right pointer one position to the left.
        j -= 1

    # If the element at the current index is 0, move the left pointer one position to the right.
    elif arr[i] == 0:
        i += 1

    # If the element at the end of the array is 1, move the right pointer one position to the left.
    elif arr[j] == 1:
        j -= 1

Example usage

arr = [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1] solve(arr, len(arr)) print(arr) # Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

JavaScript

function solve(arr) { // Initialize two pointers, one at the beginning and one at the end of the array. let i = 0; let j = arr.length - 1;

// Iterate until the two pointers meet.
while (i < j) {
    // If the element at the current index is 1 and the element at the end of the array is 0,
    // swap the two elements.
    if (arr[i] === 1 && arr[j] === 0) {
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;

        // Move the left pointer one position to the right.
        i++;

        // Move the right pointer one position to the left.
        j--;
    }
    // If the element at the current index is 0, move the left pointer one position to the right.
    else if (arr[i] === 0) {
        i++;
    }
    // If the element at the end of the array is 1, move the right pointer one position to the left.
    else if (arr[j] === 1) {
        j--;
    }
}

}

// Example usage let arr = [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1]; solve(arr); console.log("Sorted array:", arr);

`

Output

0 0 0 0 0 1 1 1 1 1 1

**Time Complexity: O(N)
**Auxiliary Space: O(1)