Segregate 0s and 1s in an array
Last Updated :
23 Jul, 2025
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array [Basically you have to sort the array]. Traverse array only once.
Input : [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
Input : [0, 1, 0]
Output : [0, 0, 1]
Input : [1, 1]
Output : [1, 1]
Input : [0]
Output : [0]
Naive Approach - Count 1s and 0s - Two Traversals
Let's understand with an example we have an array arr = [0, 1, 0, 1, 0, 0, 1] the size of the array is 7 now we will traverse the entire array and find out the number of zeros in the array, In this case the number of zeros is 4 so now we can easily get the number of Ones in the array by Array Length - Number Of Zeros. Once we have counted, we can fill the array first we will put the zeros and then ones (we can get number of ones by using above formula).
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to segregate 0s and 1s
void segregate0and1(vector<int>& arr) {
// Count 0s
int count = 0;
for (int x : arr)
if (x == 0)
count++;
// Fill the vector with 0s until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// Fill the remaining vector space with 1s
for (int i = count; i < arr.size(); i++)
arr[i] = 1;
}
int main() {
vector<int> arr = { 0, 1, 0, 1, 1, 1 };
segregate0and1(arr);
cout << "Array after segregation is ";
for (int x : arr)
cout << x << " ";
return 0;
}
C
// C code to Segregate 0s and 1s in an array
#include <stdio.h>
// Function to segregate 0s and 1s
void segregate0and1(int arr[], int n)
{
int count = 0; // Counts the no of zeros in arr
for (int i = 0; i < n; i++)
if (arr[i] == 0)
count++;
// Loop fills the arr with 0 until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// Loop fills remaining arr space with 1
for (int i = count; i < n; i++)
arr[i] = 1;
}
// Function to print segregated array
void print(int arr[], int n)
{
printf("Array after segregation is ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}
// Driver function
int main()
{
int arr[] = { 0, 1, 0, 1, 1, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
segregate0and1(arr, n);
print(arr, n);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java code to Segregate 0s and 1s in an array
import java.io.*;
public class GFG {
// function to segregate 0s and 1s
static void segregate0and1(int arr[], int n)
{
int count = 0; // counts the no of zeros in arr
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}
// loop fills the arr with 0 until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// loop fills remaining arr space with 1
for (int i = count; i < n; i++)
arr[i] = 1;
}
// function to print segregated array
static void print(int arr[], int n)
{
System.out.print("Array after segregation is ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
// driver function
public static void main(String[] args)
{
int arr[] = new int[]{ 0, 1, 0, 1, 1, 1 };
int n = arr.length;
segregate0and1(arr, n);
print(arr, n);
}
}
// This code is contributed by Kamal Rawal
Python
# Python 3 code to Segregate
# 0s and 1s in an array
# Function to segregate 0s and 1s
def segregate0and1(arr, n) :
# Counts the no of zeros in arr
count = 0
for i in range(0, n) :
if (arr[i] == 0) :
count = count + 1
# Loop fills the arr with 0 until count
for i in range(0, count) :
arr[i] = 0
# Loop fills remaining arr space with 1
for i in range(count, n) :
arr[i] = 1
# Function to print segregated array
def print_arr(arr , n) :
print( "Array after segregation is ",end = "")
for i in range(0, n) :
print(arr[i] , end = " ")
# Driver function
arr = [ 0, 1, 0, 1, 1, 1 ]
n = len(arr)
segregate0and1(arr, n)
print_arr(arr, n)
# This code is contributed by Nikita Tiwari.
C#
// C# code to Segregate 0s and 1s in an array
using System;
class GFG {
// function to segregate 0s and 1s
static void segregate0and1(int []arr, int n)
{
// counts the no of zeros in arr
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}
// loop fills the arr with 0 until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// loop fills remaining arr space with 1
for (int i = count; i < n; i++)
arr[i] = 1;
}
// function to print segregated array
static void print(int []arr, int n)
{
Console.WriteLine("Array after segregation is ");
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
// driver function
public static void Main()
{
int []arr = new int[]{ 0, 1, 0, 1, 1, 1 };
int n = arr.Length;
segregate0and1(arr, n);
print(arr, n);
}
}
//This code is contributed by vt_m.
JavaScript
<script>
// JavaScript code to Segregate 0s and 1s in an array
// Function to segregate 0s and 1s
function segregate0and1(arr, n)
{
let count = 0; // Counts the no of zeros in arr
for (let i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}
// Loop fills the arr with 0 until count
for (let i = 0; i < count; i++)
arr[i] = 0;
// Loop fills remaining arr space with 1
for (let i = count; i < n; i++)
arr[i] = 1;
}
// Function to print segregated array
function print(arr, n)
{
document.write("Array after segregation is ");
for (let i = 0; i < n; i++)
document.write(arr[i] + " ");
}
// Driver function
let arr = [ 0, 1, 0, 1, 1, 1 ];
let n = arr.length;
segregate0and1(arr, n);
print(arr, n);
// This code is contributed by Surbhi Tyagi
</script>
PHP
<?php
// PHP code to Segregate
// 0s and 1s in an array
// Function to segregate
// 0s and 1s
function segregate0and1(&$arr, $n)
{
$count = 0; // Counts the no
// of zeros in arr
for ($i = 0; $i < $n; $i++)
{
if ($arr[$i] == 0)
$count++;
}
// Loop fills the arr
// with 0 until count
for ($i = 0; $i < $count; $i++)
$arr[$i] = 0;
// Loop fills remaining
// arr space with 1
for ($i = $count; $i < $n; $i++)
$arr[$i] = 1;
}
// Function to print
// segregated array
function toprint(&$arr , $n)
{
echo ("Array after segregation is ");
for ($i = 0; $i < $n; $i++)
echo ( $arr[$i] . " ");
}
// Driver Code
$arr = array(0, 1, 0, 1, 1, 1 );
$n = sizeof($arr);
segregate0and1($arr, $n);
toprint($arr, $n);
// This code is contributed
// by Shivi_Aggarwal
?>
OutputArray after segregation is 0 0 1 1 1 1
Time Complexity : O(n)
Auxiliary Space: O(1)
The above solution has two issues
- Requires two traversals of the array.
- If 0s and 1s represent keys (say 0 means first year students and 1 means second year) of large objects associated, then the above solution would not work.
Expected Approach - One Traversal
Maintain two indexes. Initialize the first index left as 0 and second index right as n-1.
Do following while lo < hi
...a) Keep incrementing index lo while there are 0s at it
...b) Keep decrementing index hi while there are 1s at it
...c) If lo < hi then exchange arr[lo] and arr[hi]
C++
#include <iostream>
#include <vector>
using namespace std;
/* Function to put all 0s on the left and all 1s on the right */
void segregate0and1(vector<int>& arr) {
// Initialize lo and hi indexes
int lo = 0, hi = arr.size() - 1;
while (lo < hi) {
// Increment lo index while we see 0 at lo
while (arr[lo] == 0 && lo < hi)
lo++;
// Decrement hi index while we see 1 at hi
while (arr[hi] == 1 && lo < hi)
hi--;
// If lo is smaller than hi, then there is
// a 1 at lo and a 0 at hi
if (lo < hi) {
swap(arr[lo], arr[hi]);
lo++;
hi--;
}
}
}
int main() {
vector<int> arr = {0, 1, 0, 1, 1, 1};
segregate0and1(arr);
cout << "Array after segregation: ";
for (int x : arr)
cout << x << " ";
return 0;
}
C
#include <stdio.h>
void segregate0and1(int arr[], int n) {
int lo = 0, hi = n - 1;
while (lo < hi) {
while (arr[lo] == 0 && lo < hi) lo++;
while (arr[hi] == 1 && lo < hi) hi--;
if (lo < hi) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
}
}
}
int main() {
int arr[] = {0, 1, 0, 1, 1, 1};
int n = sizeof(arr) / sizeof(arr[0]);
segregate0and1(arr, n);
printf("Array after segregation: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Java
import java.util.Arrays;
public class Segregate0and1 {
public static void segregate0and1(int[] arr) {
int lo = 0, hi = arr.length - 1;
while (lo < hi) {
while (arr[lo] == 0 && lo < hi) lo++;
while (arr[hi] == 1 && lo < hi) hi--;
if (lo < hi) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 1, 1, 1};
segregate0and1(arr);
System.out.print("Array after segregation: ");
System.out.println(Arrays.toString(arr));
}
}
Python
def segregate0and1(arr):
lo, hi = 0, len(arr) - 1
while lo < hi:
while arr[lo] == 0 and lo < hi:
lo += 1
while arr[hi] == 1 and lo < hi:
hi -= 1
if lo < hi:
arr[lo], arr[hi] = arr[hi], arr[lo]
lo += 1
hi -= 1
arr = [0, 1, 0, 1, 1, 1]
segregate0and1(arr)
print("Array after segregation:", arr)
C#
using System;
using System.Linq;
class Program {
static void Segregate0and1(int[] arr) {
int lo = 0, hi = arr.Length - 1;
while (lo < hi) {
while (arr[lo] == 0 && lo < hi) lo++;
while (arr[hi] == 1 && lo < hi) hi--;
if (lo < hi) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
}
}
}
static void Main() {
int[] arr = {0, 1, 0, 1, 1, 1};
Segregate0and1(arr);
Console.WriteLine("Array after segregation: " + string.Join(" ", arr));
}
}
JavaScript
function segregate0and1(arr) {
let lo = 0, hi = arr.length - 1;
while (lo < hi) {
while (arr[lo] === 0 && lo < hi) lo++;
while (arr[hi] === 1 && lo < hi) hi--;
if (lo < hi) {
[arr[lo], arr[hi]] = [arr[hi], arr[lo]];
lo++;
hi--;
}
}
}
let arr = [0, 1, 0, 1, 1, 1];
segregate0and1(arr);
console.log("Array after segregation:", arr);
OutputArray after segregation: 0 0 1 1 1 1
Time Complexity : O(n)
Auxiliary Space: O(1)
The above approach is mainly derived from Hoare's Partition Algorithm in QuickSort
More Efficient Implementation of the Above Approach
1. Take two pointer lo (for element 0) starting from beginning (index = 0) and hi(for element 1) starting from end (index = array.length-1).
Initialize lo = 0 and hi = array.length-1
2. It is intended to Put 1 to the right side of the array. Once it is done, then 0 will definitely towards the left side of the array.
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to put all 0s on the left and
// all 1s on the right
void segregate0and1(vector<int>& arr) {
int lo = 0;
int hi = arr.size() - 1;
while (lo < hi) {
// If we have a 1 at lo
if (arr[lo] == 1) {
// And a 0 at hi
if (arr[hi] != 1) {
swap(arr[lo], arr[hi]);
lo++;
hi--;
}
else {
hi--;
}
} else {
lo++;
}
}
}
int main() {
vector<int> arr = {0, 1, 0, 1, 1, 1};
segregate0and1(arr);
cout << "Array after segregation is ";
for (int x : arr)
cout << x << " ";
return 0;
}
C
#include <stdio.h>
void segregate0and1(int arr[], int n) {
int lo = 0;
int hi = n - 1;
while (lo < hi) {
if (arr[lo] == 1) {
if (arr[hi] != 1) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
} else {
hi--;
}
} else {
lo++;
}
}
}
int main() {
int arr[] = {0, 1, 0, 1, 1, 1};
int n = sizeof(arr) / sizeof(arr[0]);
segregate0and1(arr, n);
printf("Array after segregation is ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Java
import java.util.Arrays;
public class Segregate0And1 {
public static void segregate0and1(int[] arr) {
int lo = 0;
int hi = arr.length - 1;
while (lo < hi) {
if (arr[lo] == 1) {
if (arr[hi] != 1) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
} else {
hi--;
}
} else {
lo++;
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 1, 1, 1};
segregate0and1(arr);
System.out.print("Array after segregation is ");
System.out.println(Arrays.toString(arr));
}
}
Python
def segregate0and1(arr):
lo = 0
hi = len(arr) - 1
while lo < hi:
if arr[lo] == 1:
if arr[hi] != 1:
arr[lo], arr[hi] = arr[hi], arr[lo]
lo += 1
hi -= 1
else:
hi -= 1
else:
lo += 1
arr = [0, 1, 0, 1, 1, 1]
segregate0and1(arr)
print("Array after segregation is:", arr)
C#
using System;
class Program {
static void Segregate0and1(int[] arr) {
int lo = 0;
int hi = arr.Length - 1;
while (lo < hi) {
if (arr[lo] == 1) {
if (arr[hi] != 1) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
} else {
hi--;
}
} else {
lo++;
}
}
}
static void Main() {
int[] arr = {0, 1, 0, 1, 1, 1};
Segregate0and1(arr);
Console.WriteLine("Array after segregation is: " + string.Join(" ", arr));
}
}
JavaScript
function segregate0and1(arr) {
let lo = 0;
let hi = arr.length - 1;
while (lo < hi) {
if (arr[lo] === 1) {
if (arr[hi] !== 1) {
[arr[lo], arr[hi]] = [arr[hi], arr[lo]];
lo++;
hi--;
} else {
hi--;
}
} else {
lo++;
}
}
}
let arr = [0, 1, 0, 1, 1, 1];
segregate0and1(arr);
console.log('Array after segregation is:', arr);
OutputArray after segregation is 0 0 1 1 1 1
Recommended Next Articles
Binary Array Sorting | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem