Java: Separate 0s on left side and 1s on right side of an array of 0s and 1s in random order
Java Array: Exercise-51 with Solution
Write a Java program that separates 0s on the left hand side and 1s on the right hand side from a random array of 0s and 1.
Pictorial Presentation:

Sample Solution:
Java Code:
// Import the necessary Java utility class for working with arrays.
import java.util.Arrays;
// Define the Main class.
public class Main {
public static void main(String[] args)
{
// Create an array of integers containing 0s and 1s.
int arr[] = new int[]{ 0, 0, 1, 1, 0, 1, 1, 1, 0 };
int result[];
// Print the original array.
System.out.println("Original Array ");
System.out.println(Arrays.toString(arr));
// Get the length of the array.
int n = arr.length;
// Call the separate_0_1 method to separate 0s and 1s.
result = separate_0_1(arr, n);
// Print the rearranged array.
System.out.println("New Array ");
System.out.println(Arrays.toString(result));
}
// A method to separate 0s and 1s in an array.
static int[] separate_0_1(int arr[], int n)
{
// Initialize a count to track the number of 0s.
int count = 0;
// Count the number of 0s in the array.
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}
// Set the first 'count' elements to 0.
for (int i = 0; i < count; i++)
arr[i] = 0;
// Set the remaining elements to 1.
for (int i = count; i < n; i++)
arr[i] = 1;
// Return the modified array.
return arr;
}
}
Sample Output:
Original Array [0, 0, 1, 1, 0, 1, 1, 1, 0] New Array [0, 0, 0, 0, 1, 1, 1, 1, 1]
Flowchart:

Java Code Editor:
Previous: Write a Java program to sort an array of positive integers of a given array, in the sorted array the value of the first element should be maximum, second value should be minimum value, third should be second maximum, fourth second be second minimum and so on.
Next: Write a Java program to separate even and odd numbers of a given array of integers. Put all even numbers first, and then odd numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join