Skip to content

Instantly share code, notes, and snippets.

@PJensen
Created June 18, 2021 21:43
Show Gist options
  • Save PJensen/22eee1b9294e0d9be894b76e51480cf9 to your computer and use it in GitHub Desktop.
Save PJensen/22eee1b9294e0d9be894b76e51480cf9 to your computer and use it in GitHub Desktop.
public static void moveZeros(ref int[] numbers)
{
// Create a new array of the same size, NOTE: it's already initialized with zeros
var newArray = new int[numbers.Length];
// the "otherIndex" is used to separately track non-zero entries in the copy
int otherIndex = 0;
for (int index = 0; index < numbers.Length; index++)
{
// only assign into newArray when an entry is non-zero
if (numbers[index] != 0)
{
// NOTE: incrementing otherIndex here
newArray[otherIndex++] = numbers[index];
}
}
numbers = newArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment