Java Program to Segregate 0s on Left Side & 1s on Right Side of the 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.

advertisement

Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn