Java Program to Segregate 0s and 1s in an Array

«
»
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.

advertisement
  1. public class ArraySegregate
  2. {
  3.     public static void main(String... a)
  4.     {
  5.         int array[] = { 0, 1, 0, 1, 1, 0 };
  6.         segregate0and1(array, 6);
  7.         for(int i = 0 ; i < 6; i++)
  8.         {
  9.             System.out.print(array[i]+"\t");
  10.         }
  11.     }
  12.     static void segregate0and1(int array[], int size)
  13.     {
  14.         int left = 0, right = size-1;
  15.     	while (left < right)
  16.     	{
  17.             /* Increment left index while we see 0 at left */
  18.             while (array[left] == 0 && left < right)
  19.             left++;
  20.             /* Decrement right index while we see 1 at right */
  21.             while (array[right] == 1 && left < right)
  22.             right--;
  23.             /* If left is smaller than right then there is a 1 at left and a 0 at right.  Exchange it */
  24.             if (left < right)
  25.             {
  26.                 array[left] = 0;
  27.                 array[right] = 1;
  28.                 left++;
  29.                 right--;
  30.             }
  31.         }
  32.     }
  33. }

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.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.