Created
June 18, 2021 21:43
-
-
Save PJensen/22eee1b9294e0d9be894b76e51480cf9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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