Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Convert an Array to reduced for using Binary Search
Next article icon

Sort a binary array using one traversal and no extra space

Last Updated : 26 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • 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 the index( jth ) position and increment the index j by 1.
  • If the element is 1 keep the element as it is.

Below is the implementation of the above approach:

CPP
// 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 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
<?php // PHP Code for Sort a binary // array using one traversal function 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);  // 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:

  • The function initializes two pointers i and j at the start and end of the array respectively (i at 0 and j at N-1).
  • Inside the loop, it checks if the element at index i is 1 and the element at index j is 0. If this condition is true, it swaps the elements. Then it increments i and decrements j.
  • If the element at index i is 0, it increments i. This ensures that i moves forward until it finds a 1.
  • If the element at index j is 1, it decrements j. This ensures that j moves backward until it finds a 0.

Below is the implementation of the above Approach:

C++
#include <iostream> #include <vector>  void solve(std::vector<int>& 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<int> 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)



Next Article
Convert an Array to reduced for using Binary Search

D

Devanshu Agarwal
Improve
Article Tags :
  • Misc
  • Sorting
  • DSA
  • binary-string
Practice Tags :
  • Misc
  • Sorting

Similar Reads

  • Create a Sorted Array Using Binary Search
    Given an array, the task is to create a new sorted array in ascending order from the elements of the given array.Examples: Input : arr[] = {2, 5, 4, 9, 8} Output : 2 4 5 8 9 Input : arr[] = {10, 45, 98, 35, 45} Output : 10 35 45 45 98 The above problem can be solved efficiently using Binary Search.
    9 min read
  • Sort an Array of Strings in Lexicographical order
    Given an array of strings arr[] of size n, the task is to sort all the strings in lexicographical order. Examples: Input: arr[] = ["banana", "apple", "cherry"]Output: ["apple", "banana", "cherry"]Explanation: All strings are sorted alphabetically. "apple" comes before "banana", and "banana" before "
    11 min read
  • Count inversions in an array | Set 4 ( Using Trie )
    Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then inversion count is 0. If the array is sorted in reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] > a[j] and i <
    12 min read
  • Convert an Array to reduced for using Binary Search
    Given an array arr[] consisting of N distinct integers, the task is to convert the given array into a sequence of first N non-negative integers, i.e. [0, N - 1] such that the order of the elements is the same, i.e. 0 is placed at the index of the smallest array element, 1 at the index of the second
    7 min read
  • Efficiently merging two sorted arrays with O(1) extra space and O(NlogN + MlogM)
    Given two sorted arrays, arr1[] and arr2[], the task is to merge them in O(Nlog(N) + Mlog(M)) time with O(1) extra space into a sorted array where N is the size of the first array arr1[] and M is the size of the second array arr2[]. Examples: Input: arr1[] = {1, 5, 9, 10, 15, 20}, arr2[] = {2, 3, 8,
    9 min read
  • Move all zeroes to end of array | Set-2 (Using single traversal)
    Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples: Input : arr[] = {1, 2, 0, 0, 0, 3, 6} Output : 1 2 3 6 0 0 0 Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7,
    7 min read
  • Sort given Array using at most N cyclic shift on any subarray
    Given an array arr[] containing N integers, with duplicates. The task is to sort the array in increasing order using at most N cyclic shift on any sub-array. Cyclic shift on any sub-array means cut out any subarray from the given array, use cyclic shift (rotate) in it by any offset, and put it back
    8 min read
  • Merge two sorted arrays in constant space using Min Heap
    Given two sorted arrays, we need to merge them with O(1) extra space into a sorted array, when N is the size of the first array, and M is the size of the second array. Example : Input: arr1[] = {10}; arr2[] = {2, 3};Output: arr1[] = {2} arr2[] = {3, 10} Input: arr1[] = {1, 5, 9, 10, 15, 20}; arr2[]
    8 min read
  • Sorting an Array in Bash using Insertion Sort
    Given an array, arr[] of size N, the task is to sort the array in ascending order using Insertion Sort in bash scripting. Examples: Input: arr[] = {9, 7, 2, 5}Output: 2 5 7 9Explanation: The array in sorted order is {2, 5, 7, 9} Input: arr[] = {3, 2, 1}Output: 1 2 3Explanation: The array in sorted o
    2 min read
  • Sort an array which contain 1 to n values
    We are given an array that contains 1 to n elements, our task is to sort this array in an efficient way. We are not allowed to simply copy the numbers from 1 to n.Examples : Input : arr[] = {2, 1, 3};Output : {1, 2, 3} Input : arr[] = {2, 1, 4, 3};Output : {1, 2, 3, 4} Native approach - O(n Log n) T
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences