Pages

Java Shift all zeros in array to end of array ?

Java Shift all zeros in array to end of array ?

  • In Java we can shift all zeros in array to end/right of array using for loop.
public class shiftZeros {
public static void main(String[] args) {
int arr[] = { 0, 1, 0, 0, 6, 13, 0, 6, 0, 8, 5, 0, 2, 0, 4, 0, 5, -1, -4 };
int
temp;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == 0) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

for (int n : arr) {
System.out.
print(n + " ");
}
}
}
Output:
Java  Shift all zeros in array to end of array
Java Shift all zeros in array to end of array
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.