If I have the next array:
int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 };
How can I move all the values which are not equal to 0 left as they can so the array will be built like this:
int[] arr = { 123, 243, 123, 123, 0, 0, 0, 0, 0 };
Thanks!
How about with LINQ:
var result = arr.Where(x => x != 0).Concat(arr.Where(x => x == 0)).ToArray();
This is quite readable and has linear time complexity. On the other hand, it runs out-of-place and requires two passes over the input.
OrderBy:
int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 }.OrderBy(x => x == 0).ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With