Segregate all zeroes to start of array.

 Problem: You have an array of 0's and 1's. Segregate them such that 0's are at left and 1's at right.

App.java


public class App {
    public static void main(String[] args) throws Exception {
        // [1,0,1,0,1,0,1,0,1,0] ==> [0,0,0,0,0,1,1,1,1,1]
        int[] arr = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 };

        segerate0s1sFromArray(arr);
        printArray(arr);
        /*
         * int count = 0;
         * for (int i = 0; i < arr.length; i++) {
         * if (arr[i] == 0) {
         * arr[count++] = 0;
         * }
         * }
         * for (int i = count; i < arr.length; i++) {
         *
         * arr[i] = 1;
         * }
         */
    }

    private static void segerate0s1sFromArray(int[] arr) {
        // { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 };
        int left = 0;
        int right = arr.length - 1;
        if (arr.length < 1) {
            return;
        }
        while (left < right) {
            while (arr[left] % 2 == 0 && left < right) {
                left++;
            }

            while (arr[right] % 2 == 1 && left < right) {
                right--;
            }

            // swap left and right
            if (left < right) {
                int x = arr[left];
                arr[left] = arr[right];
                arr[right] = x;

                left++;
                right--;

            }
        }

    }

    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
Output :

    0
    0
    0
    0
    0
    1
    1
    1
    1
    1


Comments