Given an array of length N consisting of only 0s and 1s in random order. Modify the array to segregate 0s on left side and 1s on the right side of the array

Given an array of length N consisting of only 0s and 1s in random order. Modify the array to segregate 0s on left side and 1s on the right side of the array.






Example 1:

Input:
N = 5
arr[] = {0, 0, 1, 1, 0}
Output: 0 0 0 1 1


Example 2:

Input:
N = 4
Arr[] = {1, 1, 1, 1}
Output: 1 1 1 1
Explanation: There are no 0 in the given array, 
so the modified array is 1 1 1 1.


Solution  


class Solution
{
public:
void segregate0and1(int arr[], int n)
{
int low = -1, high = n;

while(true)
{
do
{
low++;
}
while(arr[low] == 0);

do
{
high--;
}
while(arr[high] == 1);

if(low > high)
{
return;
}

swap(arr[low], arr[high]);
}
}
};


Hope you find this article useful. 









Post a Comment

If you have furthur QUERIES please let us know

Previous Post Next Post