Moving all zeros to the end of an array in C# can be achieved using a simple algorithm. Below is a step-by-step explanation along with a sample code implementation.
Explanation
-
Two Pointers Technique: We can use two pointers to manage the position of non-zero elements and the position to place the next non-zero element.
-
Iterate Through the Array: Loop through each element of the array. If the element is not zero, we place it at the index tracked by one of the pointers.
-
Fill Remaining Elements: After all non-zero elements have been moved to the front, we fill the remaining positions in the array with zeros.
Code Implementation
Here’s how you can implement this in C#:
using System;
class Program
{
static void MoveZeroes(int[] nums)
{
int nonZeroIndex = 0; // Pointer for the position of the next non-zero element
// First pass: move non-zero elements to the front
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] != 0)
{
nums[nonZeroIndex] = nums[i];
nonZeroIndex++;
}
}
// Second pass: fill the remaining positions with zeroes
for (int i = nonZeroIndex; i < nums.Length; i++)
{
nums[i] = 0;
}
}
static void Main(string[] args)
{
int[] arr = { 0, 1, 0, 3, 12 };
MoveZeroes(arr);
Console.WriteLine(string.Join(", ", arr)); // Output: 1, 3, 12, 0, 0
}
}
How the Code Works
-
Initialize a Non-Zero Index: We start by initializing
nonZeroIndex
to keep track of where the next non-zero element should go. -
First Loop (Moving Non-Zero Elements):
- We iterate through each element of the array.
- If the current element is not zero, we place it at the
nonZeroIndex
and then incrementnonZeroIndex
.
-
Second Loop (Filling Zeros):
- After all non-zero elements are placed, the second loop fills the rest of the array with zeros starting from the
nonZeroIndex
to the end of the array.
- After all non-zero elements are placed, the second loop fills the rest of the array with zeros starting from the
Complexity
- Time Complexity: O(n), where n is the number of elements in the array, since we traverse the array a couple of times.
- Space Complexity: O(1), as we are not using any extra space proportional to the input size; we are modifying the array in place.
This method is efficient and straightforward, making it a common approach for solving the problem of moving zeros to the end of an array.