Move Zeros to First Position array java programme

 import java.util.Arrays;


public class ZerosToFirstPosition {

   public static void bringZerosToLastPosition(int[] a){
    //We need to add current at last position of index.
int current= 0;

//we need to reverse iterate
for(int i= 0;i<a.length;i++){
if (a[i] != 0) {
a[current] = a[i];
current++;
}
}

while (current <= a.length-1) {
a[current] = 0;
current++;
}

System.out.println(Arrays.toString(a));
}

public static void bringZerosToFirstPosition(int[] a){
//We need to add current at last position of index.
int current= a.length-1;

//we need to reverse iterate
for(int i= a.length-1;i>=0;i--){
if (a[i] != 0) {
a[current] = a[i];
current--;
}
}

while (current >= 0) {
a[current] = 0;
current--;
}

System.out.println(Arrays.toString(a));
}

public static void main(String[] args) {

int[] array = {1, 2, 0};
bringZerosToFirstPosition(array);
}
}

Comments