Segregate 0s and 1s in an array
Asked by kapil.
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. Traverse array only once.
Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
Method 1 (Count 0s or 1s)
Thanks to Naveen for suggesting this method.
1) Count the number of 0s. Let count be C.
2) Once we have count, we can put C 0s at the beginning and 1s at the remaining n – C positions in array.
Time Complexity: O(n)
The 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 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:
#include<stdio.h>
/*Function to put all 0s on left and all 1s on right*/
void segregate0and1(int arr[], int size)
{
/* Initialize left and right indexes */
int 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 program to test */
int main()
{
int arr[] = {0, 1, 0, 1, 1, 1};
int arr_size = 6, i = 0;
segregate0and1(arr, arr_size);
printf("array after segregation ");
for(i = 0; i < 6; i++)
printf("%d ", arr[i]);
getchar();
return 0;
}
Time Complexity: O(n)
Please write comments if you find any of the above algorithms/code incorrect, or a better ways to solve the same problem.


[Update]
public static void Segregate0sAnd1sUsingTempArray(ref int[] array) { int[] temp = new int[array.Length]; int OnesCounter = array.Length - 1; for (int i = 0; i < array.Length; i++) { if (array[i] == 0) { temp[OnesCounter] = 1; OnesCounter--; } } array = temp; }The above code is in Java. If I understand it correctly, it’s working as follows:
1. temp array is created which might be initialized with zeros.
2. And we are setting the elements to one in temp from the back if we find any zero in array from front.
3. So temp would have exactly same number of ones at the back what array has number of zeros
4. So assigning temp to array wouldn’t solve the problem.
Am I missing anything, Sam?
Using Temp array and only one traversal.
public static void Segregate0sAnd1sUsingTempArray(ref int[] array) { int[] temp = new int[array.Length]; int ZerosCounter = array.Length - 1; for (int i = 0; i < array.Length; i++) { if (array[i] == 0) { temp[ZerosCounter] = 1; ZerosCounter--; } } array = temp; }i think it is like
if ( array[i]==1) { temp[onescount]=1; onescout--; }