Knowee
Questions
Features
Study Tools

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

Question

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

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple Java program that segregates all 0s on the left side and all 1s on the right side of a given array of 0s and 1s.

public class Main {
    static void segregate0and1(int arr[], int n) {
        int count = 0; // counts the no of zeros in arr

        for (int i = 0; i < n; i++) {
            if (arr[i] == 0) {
                count++;
            }
        }

        // loop fills the arr with 0 until count
        for (int i = 0; i < count; i++) {
            arr[i] = 0;
        }

        // loop fills remaining arr elements with 1
        for (int i = count; i < n; i++) {
            arr[i] = 1;
        }
    }

    // function to print segregated array
    static void print(int arr[], int n) {
        System.out.print("Array after segregation is ");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    public static void main(String[] args) {
        int arr[] = new int[]{0, 1, 0, 1, 1, 1};
        int n = arr.length;

        segregate0and1(arr, n);
        print(arr, n);
    }
}

This program works by first counting the number of 0s in the array. Then it fills the array with 0s up to the count, and fills the rest of the array with 1s. The result is an array with all 0s on the left and all 1s on the right.

This problem has been solved

Similar Questions

Write a Java program to remove the duplicate elements of a given array and return the new length of the array

Write a java program to implement interfaces sort the set of numbers and a set of strings in a given array

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

Write a Java program to remove the duplicate elements of a given array and return the new length of the array.

Write a java method to reverse the elements of an array using recursion. Your method should take an array as an input parameter and return reverse the array

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.