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.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Programming Books
- Apply for Information Technology Internship
- Practice Information Technology MCQs
- Practice Programming MCQs
- Apply for Java Internship