122k views
22 votes
Write a function: void pushZero(int[] A) that accepts an integer array A. The function should convert the original array as per above requirement.

1 Answer

8 votes

Answer:

The function is as follows

public static void pushZero(int[] A){

int curr = A.length - 1;

for (int i = A.length - 1; i >= 0; i--) {

if (A[i] != 0) {

A[curr] = A[i];

curr--;

} }

while (curr >= 0) {

A[curr] = 0;

curr--; }

for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");

} }

Step-by-step explanation:

Given

See attachment for complete question

Required

Write a function to move all 0s to the beginning of the array

The function is defined here

public static void pushZero(int[] A){

This sets the current element to the last element

int curr = A.length - 1;

This for loop through the array backwards

for (int i = A.length - 1; i >= 0; i--) {

This condition checks if the current element is not 0

if (A[i] != 0) {

Set the current element to the current iterating element of the array

A[curr] = A[i];

curr--;

} }

This while iteration is repeated while the current element is greater than 0

while (curr >= 0) {

Set current element to 0

A[curr] = 0;

curr--; }

The following for loop prints the sorted array

for (int i = 0; i < A.length; i++) {

System.out.print(A[i] + " ");

} }

Write a function: void pushZero(int[] A) that accepts an integer array A. The function-example-1
User Martin Meeser
by
7.1k points