public class Segregate0and1 {
static void segregate0and1(int arr[])
{
int type0 = 0;
int type1 = 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++;
}
}
}
public static void main(String[] args)
{
int[] array = { 0, 1, 0, 1, 1, 1 };
segregate0and1(array);
for (int a : array) {
System.out.print(a + " ");
}
//Time complexity: O(n)
//Auxiliary Space: O(1)
}
}
TechInsiderStory is place where you can find basic knowledge of various technology and framework. TechInsiderStory is provide free knowledge on various technology and framework.
Segregate0and1
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment