Q:

Write a Java program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s

belongs to collection: Array Programs in Java with Examples

0

Write a Java program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

import java.util.*;
import java.lang.*;
public class Javaexcercise
{
   public static void main (String[] args) 
    {  
        int nums[] = {1,1,0,1,0,1,1,1,0,0,0};
        int  nums_size = nums.length;
        int left = 0, right = nums_size - 1;
 
        System.out.println("Original Array : "+Arrays.toString(nums));  
 
        while (left < right) 
        {
 
            while (nums[left] == 0 && left < right)
               left++; 
 
            while (nums[right] == 1 && left < right)
                right--;
 
 
            if (left < right) 
            {
                nums[left] = 0;
                nums[right] = 1;
                left++;
                right--;
            }
        }
 
       System.out.println("Array after segregation is : "+Arrays.toString(nums));  
    }
}

Result:

Original Array : [1, 1, 0, 1,0, 1, 1, 1, 0, 0, 0]

Array after segregation is : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Array Programs in Java with Examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a Java program to cyclically rotate a given ... >>
<< Write a Java program to get the difference between...