This code defines a function `moveZeroes` that moves all zero...
This code defines a function moveZeroes
that moves all zero elements in an array to the end while maintaining the relative order of the non-zero elements. Here's what the code does in detail:
Step-by-step Explanation:
-
The
moveZeroes
function takes two parameters:arr
: The array to process.n
: The size of the array.
-
Inside the
moveZeroes
function:-
A variable
insertPos
is initialized to0
. This keeps track of the position to place the next non-zero element. -
A loop iterates through all elements of the array:
- If the current element is not zero (
arr[i] != 0
), it is moved to the position indicated byinsertPos
, andinsertPos
is incremented.
- If the current element is not zero (
-
After processing all elements,
insertPos
points to the position where zeros should start. A while loop then fills the rest of the array (frominsertPos
to the end) with zeros.
-
-
In the
main
function:- A test array
arr
with elements{0, 1, 0, 3, 12}
is defined. - The size of the array (
n
) is computed. - The
moveZeroes
function is called to process the array.
- A test array
-
After the
moveZeroes
function processes the array:- The array is updated such that all zeros are moved to the end, and the relative order of the non-zero elements remains unchanged.
- The updated array is printed using a loop.
Example Execution:
For the input array {0, 1, 0, 3, 12}
, the steps are:
- Non-zero elements
{1, 3, 12}
are moved to the front of the array. - The remaining positions are filled with zeros.
- Final array after processing:
{1, 3, 12, 0, 0}
.
Output:
After moving zeroes: 1 3 12 0 0
Summary:
The code reorders the input array so that all zeros are moved to the end, while preserving the order of all non-zero elements.