Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. The problem link is here.
Examples:
move_zeros(10, int [] {1, 2, 0, 1, 0, 1, 0, 3, 0, 1}); // -> int [] {1, 2, 1, 1, 3, 1, 0, 0, 0, 0}
Sample Tests:
Test(move_zeros, sample_tests) {
do_test(8, ((int []) {0, 1, 0, 2, 0, 3, 4, 5}), ((int []) {1, 2, 3, 4, 5, 0, 0, 0}));
do_test(20, ((int []) {9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9}), ((int []) {9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}));
do_test(2, ((int []) {0, 0}), ((int []) {0, 0}));
do_test(1, ((int []) {0}), ((int []) {0}));
do_test(0, ((int []) {}), ((int []) {}));
}
Solution:
#include <stddef.h>
void move_zeros(size_t len, int arr[len])
{
// mutate arr in place
size_t i, j, k, temp;
for (i = 0; i < len; i++)
{
if (arr[i] == 0)
{
k = i;
for (j = i + 1; j < len; j++)
{
if (arr[j] != 0)
{
temp = arr[j];
arr[j] = 0;
arr[k] = temp;
k = j;
}
}
}
}
}