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.
Method 1 (Count 0s or 1s) Thanks to Naveen for suggesting this method. 1) Count the number of 0s. So 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.
2) 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). Time Complexity : O(n)
C++
// C++ code to Segregate 0s and 1s in an array
#include <bits/stdc++.h>
usingnamespacestd;
// Function to segregate 0s and 1s
voidsegregate0and1(intarr[], intn)
{
intcount = 0; // Counts the no of zeros in arr
for(inti = 0; i < n; i++) {
if(arr[i] == 0)
count++;
}
// Loop fills the arr with 0 until count
for(inti = 0; i < count; i++)
arr[i] = 0;
// Loop fills remaining arr space with 1
for(inti = count; i < n; i++)
arr[i] = 1;
}
// Function to print segregated array
voidprint(intarr[], intn)
{
cout << "Array after segregation is ";
for(inti = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver function
intmain()
{
intarr[] = { 0, 1, 0, 1, 1, 1 };
intn = sizeof(arr) / sizeof(arr[0]);
segregate0and1(arr, n);
print(arr, n);
return0;
}
// This code is contributed by Sahil_Bansall
Java
// Java code to Segregate 0s and 1s in an array
classGFG {
// function to segregate 0s and 1s
staticvoidsegregate0and1(intarr[], intn)
{
intcount = 0; // counts the no of zeros in arr
for(inti = 0; i < n; i++) {
if(arr[i] == 0)
count++;
}
// loop fills the arr with 0 until count
for(inti = 0; i < count; i++)
arr[i] = 0;
// loop fills remaining arr space with 1
for(inti = count; i < n; i++)
arr[i] = 1;
}
// function to print segregated array
staticvoidprint(intarr[], intn)
{
System.out.print("Array after segregation is ");
for(inti = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
// driver function
publicstaticvoidmain(String[] args)
{
intarr[] = newint[]{ 0, 1, 0, 1, 1, 1};
intn = arr.length;
segregate0and1(arr, n);
print(arr, n);
}
}
// This code is contributed by Kamal Rawal
Python3
# Python 3 code to Segregate
# 0s and 1s in an array
# Function to segregate 0s and 1s
defsegregate0and1(arr, n) :
# Counts the no of zeros in arr
count =0
fori inrange(0, n) :
if(arr[i] ==0) :
count =count +1
# Loop fills the arr with 0 until count
fori inrange(0, count) :
arr[i] =0
# Loop fills remaining arr space with 1
fori inrange(count, n) :
arr[i] =1
# Function to print segregated array
defprint_arr(arr , n) :
print( "Array after segregation is ",end ="")
fori inrange(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
usingSystem;
classGFG {
// function to segregate 0s and 1s
staticvoidsegregate0and1(int[]arr, intn)
{
// counts the no of zeros in arr
intcount = 0;
for(inti = 0; i < n; i++) {
if(arr[i] == 0)
count++;
}
// loop fills the arr with 0 until count
for(inti = 0; i < count; i++)
arr[i] = 0;
// loop fills remaining arr space with 1
for(inti = count; i < n; i++)
arr[i] = 1;
}
// function to print segregated array
staticvoidprint(int[]arr, intn)
{
Console.WriteLine("Array after segregation is ");
for(inti = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
// driver function
publicstaticvoidMain()
{
int[]arr = newint[]{ 0, 1, 0, 1, 1, 1 };
intn = arr.Length;
segregate0and1(arr, n);
print(arr, n);
}
}
//This code is contributed by vt_m.
PHP
<?php
// PHP code to Segregate
// 0s and 1s in an array
// Function to segregate
// 0s and 1s
functionsegregate0and1(&$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
functiontoprint(&$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
?>
Javascript
<script>
// JavaScript code to Segregate 0s and 1s in an array
// Function to segregate 0s and 1s
functionsegregate0and1(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
functionprint(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>
Output
Array after segregation is 0 0 1 1 1 1
Method 1 traverses the array two times. Method 2 does the same in a single pass.
Method 2 (Use two indexes to traverse) Maintain two indexes. Initialize the first index left as 0 and second index right as n-1. Do following while left < right a) Keep incrementing index left while there are 0s at it b) Keep decrementing index right while there are 1s at it c) If left < right then exchange arr[left] and arr[right]
Implementation:
C++
// C++ program to sort a binary array in one pass
#include <bits/stdc++.h>
usingnamespacestd;
/*Function to put all 0s on left and all 1s on right*/
voidsegregate0and1(intarr[], intsize)
{
/* Initialize left and right indexes */
intleft = 0, right = size-1;
while(left < right)
{
/* Increment left index while we see 0 at left */
while(arr[left] == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while(arr[right] == 1 && left < right)
right--;
/* If left is smaller than right then there is a 1 at left
and a 0 at right. Exchange arr[left] and arr[right]*/
if(left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
/* Driver code */
intmain()
{
intarr[] = {0, 1, 0, 1, 1, 1};
inti, arr_size = sizeof(arr)/sizeof(arr[0]);
segregate0and1(arr, arr_size);
cout << "Array after segregation ";
for(i = 0; i < 6; i++)
cout << arr[i] << " ";
return0;
}
// This is code is contributed by rathbhupendra
C
// C program to sort a binary array in one pass
#include<stdio.h>
/*Function to put all 0s on left and all 1s on right*/
voidsegregate0and1(intarr[], intsize)
{
/* Initialize left and right indexes */
intleft = 0, right = size-1;
while(left < right)
{
/* Increment left index while we see 0 at left */
while(arr[left] == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while(arr[right] == 1 && left < right)
right--;
/* If left is smaller than right then there is a 1 at left
and a 0 at right. Exchange arr[left] and arr[right]*/
if(left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
/* driver program to test */
intmain()
{
intarr[] = {0, 1, 0, 1, 1, 1};
inti, arr_size = sizeof(arr)/sizeof(arr[0]);
segregate0and1(arr, arr_size);
printf("Array after segregation ");
for(i = 0; i < 6; i++)
printf("%d ", arr[i]);
getchar();
return0;
}
Java
classSegregate
{
/*Function to put all 0s on left and all 1s on right*/
voidsegregate0and1(intarr[], intsize)
{
/* Initialize left and right indexes */
intleft = 0, right = size - 1;
while(left < right)
{
/* Increment left index while we see 0 at left */
while(arr[left] == 0&& left < right)
left++;
/* Decrement right index while we see 1 at right */
while(arr[right] == 1&& left < right)
right--;
/* If left is smaller than right then there is a 1 at left
and a 0 at right. Exchange arr[left] and arr[right]*/
if(left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
/* Driver Program to test above functions */
publicstaticvoidmain(String[] args)
{
Segregate seg = newSegregate();
intarr[] = newint[]{0, 1, 0, 1, 1, 1};
inti, arr_size = arr.length;
seg.segregate0and1(arr, arr_size);
System.out.print("Array after segregation is ");
for(i = 0; i < 6; i++)
System.out.print(arr[i] + " ");
}
}
Python
# Python program to sort a binary array in one pass
# Function to put all 0s on left and all 1s on right
defsegregate0and1(arr, size):
# Initialize left and right indexes
left, right =0, size-1
whileleft < right:
# Increment left index while we see 0 at left
whilearr[left] ==0andleft < right:
left +=1
# Decrement right index while we see 1 at right
whilearr[right] ==1andleft < right:
right -=1
# If left is smaller than right then there is a 1 at left
# and a 0 at right. Exchange arr[left] and arr[right]
ifleft < right:
arr[left] =0
arr[right] =1
left +=1
right -=1
returnarr
# driver program to test
arr =[0, 1, 0, 1, 1, 1]
arr_size =len(arr)
print("Array after segregation")
print(segregate0and1(arr, arr_size))
# This code is contributed by Pratik Chhajer
C#
// C# program to sort a binary array in one pass
usingSystem;
classSegregate
{
/*Function to put all 0s on
left and all 1s on right*/
voidsegregate0and1(int[]arr, intsize)
{
/* Initialize left and right indexes */
intleft = 0, right = size - 1;
while(left < right)
{
/* Increment left index while
we see 0 at left */
while(arr[left] == 0 && left < right)
left++;
/* Decrement right index while
we see 1 at right */
while(arr[right] == 1 && left < right)
right--;
/* If left is smaller than right then
there is a 1 at left and a 0 at right.
Exchange arr[left] and arr[right]*/
if(left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
/* Driver Program to test above functions */
publicstaticvoidMain()
{
Segregate seg = newSegregate();
int[]arr = newint[]{0, 1, 0, 1, 1, 1};
inti, arr_size = arr.Length;
seg.segregate0and1(arr, arr_size);
Console.WriteLine("Array after segregation is ");
for(i = 0; i < 6; i++)
Console.Write(arr[i] + " ");
}
}
//This code is contributed by vt_m.
PHP
<?php
// PHP program to sort a
// binary array in one pass
// Function to put all 0s on
// left and all 1s on right
functionsegregate0and1(&$arr, $size)
{
// Initialize left and
// right indexes
$left= 0;
$right= $size- 1;
while($left< $right)
{
// Increment left index
// while we see 0 at left
while($arr[$left] == 0 &&
$left< $right)
$left++;
// Decrement right index
// while we see 1 at right
while($arr[$right] == 1 &&
$left< $right)
$right--;
// If left is smaller than right
// then there is a 1 at left
// and a 0 at right. Exchange
// arr[left] and arr[right]
if($left< $right)
{
$arr[$left] = 0;
$arr[$right] = 1;
$left++;
$right--;
}
}
}
// Driver code
$arr= array(0, 1, 0, 1, 1, 1);
$arr_size= sizeof($arr);
segregate0and1($arr, $arr_size);
printf("Array after segregation is ");
for($i= 0; $i< 6; $i++)
echo($arr[$i]. " ");
// This code is contributed
// by Shivi_Aggarwal
?>
Javascript
<script>
// Javascript program to sort a binary array in one pass
/*Function to put all 0s on left and all 1s on right*/
functionsegregate0and1(arr, size)
{
/* Initialize left and right indexes */
let left = 0, right = size-1;
while(left < right)
{
/* Increment left index while we see 0 at left */
while(arr[left] == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while(arr[right] == 1 && left < right)
right--;
/* If left is smaller than right then there is a 1 at left
and a 0 at right. Exchange arr[left] and arr[right]*/
if(left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
/* Driver code */
let arr = [0, 1, 0, 1, 1, 1];
let i, arr_size = arr.length;
segregate0and1(arr, arr_size);
document.write("Array after segregation ");
for(i = 0; i < 6; i++)
document.write(arr[i] + " ");
</script>
Output
Array after segregation 0 0 1 1 1 1
Time Complexity: O(n)
Another approach : 1. Take two pointer type0(for element 0) starting from beginning (index = 0) and type1(for element 1) starting from end (index = array.length-1). Initialize type0 = 0 and type1 = 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++
// C++ program to sort a
// binary array in one pass
#include <bits/stdc++.h>
usingnamespacestd;
/*Function to put all 0s on
left and all 1s on right*/
voidsegregate0and1(intarr[], intsize)
{
inttype0 = 0;
inttype1 = size - 1;
while(type0 < type1) {
if(arr[type0] == 1) {
if(arr[type1] != 1) {
swap(arr[type0], arr[type1]);
}
type1--;
}
else
type0++;
}
}
// Driver Code
intmain()
{
intarr[] = { 0, 1, 0, 1, 1, 1 };
inti, arr_size = sizeof(arr) / sizeof(arr[0]);
segregate0and1(arr, arr_size);
cout << "Array after segregation is ";
for(i = 0; i < arr_size; i++)
cout << arr[i] << " ";
return0;
}
Java
// Java code to segregate 0 and 1
importjava.util.*;
classGFG {
/**
Method for segregation 0 and 1 given input array
*/
staticvoidsegregate0and1(intarr[])
{
inttype0 = 0;
inttype1 = arr.length - 1;
while(type0 < type1) {
if(arr[type0] == 1) {
if(arr[type1] != 1) {
// swap
arr[type1] = arr[type1] + arr[type0];
arr[type0] = arr[type1] - arr[type0];
arr[type1] = arr[type1] - arr[type0];
}
type1--;
}
else{
type0++;
}
}
}
// Driver program
publicstaticvoidmain(String[] args)
{
int[] array = { 0, 1, 0, 1, 1, 1};
segregate0and1(array);
for(inta : array) {
System.out.print(a + " ");
}
}
}
Python3
# Python program to sort a
# binary array in one pass
# Function to put all 0s on
# left and all 1s on right
defsegregate0and1(arr, size):
type0 =0
type1 =size -1
while(type0 < type1):
if(arr[type0] ==1):
if(arr[type1] !=1):
(arr[type0],
arr[type1]) =(arr[type1],
arr[type0])
type1 -=1
else:
type0 +=1
# Driver Code
arr =[0, 1, 0, 1, 1, 1]
arr_size =len(arr)
segregate0and1(arr, arr_size)
print("Array after segregation is",
end =" ")
fori inrange(0, arr_size):
print(arr[i], end =" ")
# This code is contributed
# by Shivi_Aggarwal
C#
// C# code to segregate 0 and 1
usingSystem;
classGFG {
// Method for segregation 0
// and 1 given input array
staticvoidsegregate0and1(int[] arr)
{
inttype0 = 0;
inttype1 = arr.Length - 1;
while(type0 < type1) {
if(arr[type0] == 1) {
if(arr[type1] != 1) {
// swap
arr[type1] = arr[type1] + arr[type0];
arr[type0] = arr[type1] - arr[type0];
arr[type1] = arr[type1] - arr[type0];
}
type1--;
}
else{
type0++;
}
}
}
// Driver Code
publicstaticvoidMain(string[] args)
{
int[] array = newint[] { 0, 1, 0, 1, 1, 1 };
segregate0and1(array);
Console.Write("Array after segregation is ");
foreach(inta inarray) { Console.Write(a + " "); }
}
}
// This code is contributed by Shrikant13
PHP
<?php
// PHP program to sort a
// binary array in one pass
// Function to put all 0s on
// left and all 1s on right
functionsegregate0and1(&$arr, $size)
{
$type0= 0;
$type1= $size- 1;
while($type0< $type1)
{
if($arr[$type0] == 1)
{
if($arr[$type1] != 1)
{
$temp= $arr[$type0];
$arr[$type0] = $arr[$type1];
$arr[$type1] = $temp;
}
$type1--;
}
else
$type0++;
}
}
// Driver Code
$arr= array(0, 1, 0, 1, 1, 1);
$arr_size= sizeof($arr);
segregate0and1($arr, $arr_size);
echo("Array after segregation is ");
for($i= 0; $i< $arr_size; $i++)
echo($arr[$i] . " ");
// This code is contributed
// by Shivi_Aggarwal
?>
Javascript
<script>
// Javascript program to sort a
// binary array in one pass
// Function to put all 0s on
// left and all 1s on right
functionsegregate0and1(arr, size)
{
let type0 = 0;
let type1 = size - 1;
while(type0 < type1)
{
if(arr[type0] == 1)
{
if(arr[type1] != 1)
{
// Swap
arr[type1] = arr[type1] + arr[type0];
arr[type0] = arr[type1] - arr[type0];
arr[type1] = arr[type1] - arr[type0];
}
type1--;
}
else
type0++;
}
}
// Driver Code
let arr = [ 0, 1, 0, 1, 1, 1 ];
let i, arr_size = arr.length;
segregate0and1(arr, arr_size);
document.write("Array after segregation is ");
for(i = 0; i < arr_size; i++)
document.write(arr[i] + " ");
// This code is contributed by subhammahato348
</script>
Output
Array after segregation is 0 0 1 1 1 1
Time complexity: O(n) // Thanks san4net for suggesting this method.
Please write comments if you find any of the above algorithms/code incorrect, or a better way to solve the same problem.
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