Move All elements to end of array

Move All elements to end of array

This problem can be solved by maintaining counter for non-zero elements. If a non-zero element is found it is inserted to next of previous non-zero element. And the index where the element is found is set to zero.

Code:

import java.util.*;

public class Test{
    
  public static void main(String[] args) {
    
    Scanner in = new Scanner(System.in);
    int[] a = {1, 2, 0, 0, 0, 3, 6};
    int n = a.length;
    int positivecount = -1;
    for(int i=0; i<n; i++){
        if(a[i]!=0){
            positivecount++;
            if(i!=positivecount ){
                a[positivecount] = a[i];
                a[i] = 0;
            }
        }
    }
      
    for(int i=0; i<n; i++){
        System.out.print(" "+a[i]);
    }
      
  }
}

Test Run

Output:
1 2 3 6 0 0 0

Explanation:
At i = 5,
  positivecount = 3 not equal to i(5)
   hence a[5] which is 3 is assigned to a[3] and a[5] is set to zero

Similarly at i=6,
   positivecount = 4, not equal to i(6)
  hence a[6] which is 6 is assigned to a[4] and a[6] is set to zero

Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Find Maximum in Binary Tree