Saturday, August 9, 2014

Given an array of integers. Segregate all the non-zero numbers at the beginning. Print the number of non-zero integers and the minimum number of swaps required for these operations.Eg. : I/p : 1, 0, 0, -6, 2, 0o/p : Number of non-zero integers : 3

import java.util.ArrayList;

/**
 * Created by Arun on 8/9/14.
 */
public class ArrayNonZero {
    public static void main(String args[]) {
        int arr []  = {1, 0, 0, -6, 2, 0};
        ArrayList<Integer> nonZero = new ArrayList<Integer>();
        ArrayList<Integer> zero = new ArrayList<Integer>();
        int i=0;
      //get the indexes of the zero and non zero elements
        for(int val: arr) {
            if(val!=0) {
                nonZero.add(i);
            }
            else {
                zero.add(i);
            }
            i++;
        }
        int newArr [] = new int[arr.length];
        i=0;
       //put the non-zero elements at the end and zero element at the beginning
        for(int val: nonZero){
            newArr[i]=arr[val];
            i++;
        }
        for(int val: zero) {
            newArr[i] = arr[val];
            i++;
        }
        for(int val: newArr){
            System.out.println(val);
        }
    }
}

No comments:

Post a Comment