How to move all zeros in int array to the end with Java

1 Answer

0 votes
public class MyClass {
    static void move_zeros_to_end(int arr[]) { 
        int j = 0, len = arr.length;  
        
        for (int i = 0; i < len; i++) 
            if (arr[i] != 0) 
                arr[j++] = arr[i]; 
        
        while (j < len) 
            arr[j++] = 0; 
    } 
    public static void main(String args[]) {
       int[] arr= {0, 3, 4, 0, 6, 0, 0, 8, 9, 0}; 
        
        move_zeros_to_end(arr); 

        for (int i=0; i < arr.length; i++) 
            System.out.print(arr[i] + " "); 
    }
}


/*
run:

3 4 6 8 9 0 0 0 0 0 

*/

 



answered Feb 25, 2019 by avibootz

Related questions

1 answer 237 views
1 answer 235 views
1 answer 286 views
1 answer 238 views
2 answers 322 views
1 answer 276 views
2 answers 269 views
...