This is a Java Program to Segregate 0s on Left Side & 1s on Right Side of the Array.
Here is a function to segregate all 0s on left and all 1s on right as segregate0and1. We define an array and pass this array along with its length to the function and segregate 0s and 1s using this function.
Here is the source code of the Java Program to Segregate 0s on Left Side & 1s on Right Side of the Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class ArraySegregate
{
public static void main(String... a)
{
int array[] = { 0, 1, 0, 1, 1, 0 };
segregate0and1(array, 6);
for(int i = 0 ; i < 6; i++)
{
System.out.print(array[i]+"\t");
}
}
static void segregate0and1(int array[], int size)
{
int left = 0, right = size-1;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (array[left] == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (array[right] == 1 && left < right)
right--;
/* If left is smaller than right then there is a 1 at left and a 0 at right. Exchange it */
if (left < right)
{
array[left] = 0;
array[right] = 1;
left++;
right--;
}
}
}
}
Output:
$ javac ArraySegregate.java $ java ArraySegregate 0 0 0 1 1 1
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Check Java Books
- Apply for Computer Science Internship
- Practice Programming MCQs
- Practice Information Technology MCQs
- Practice BCA MCQs