Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving all zeros to the begining of array

Tags:

arrays

c

I'm trying to write a function which moves all numbers from begining of array to the end of it. order should not change.

for example i have this array:

1, 2, 3, 4, 5, 0, 0, 0, 0

i want to change it to:

0, 0, 0, 0, 1, 2, 3, 4, 5

I already wrote a version of it but it can't keep the order. (array[] is original and a[] is sorted)

#include <stdio.h>
#define SIZE_MAX 20

int main()
{
    int array[SIZE_MAX] = {1, 2, 3, 4, 5, 0, 0, 0, 0};
    int a[SIZE_MAX];
    int i;
    int p = 0;

    for (i = SIZE_MAX-1; i >= 0; i--, p++)
    {
        a[i] = array[p];
    }

    for (i = 0; i < SIZE_MAX; i++)
    {
        printf("%d", a[i]);
    }
}
like image 208
vvvsg Avatar asked Dec 06 '25 02:12

vvvsg


1 Answers

One option would be to loop through the array twice, first copying over the zeros, then the rest of the values:

#include <stdio.h>
#define SIZE_MAX 10

int main()
{
    int array[SIZE_MAX] = {1, 2, 0, 0, 3, 4, 5, 0, 0, 0};
    int a[SIZE_MAX];
    int i;
    int p = 0;

    for (i = 0; i < SIZE_MAX; ++i) {
        if (array[i] == 0) {
            a[p++] = 0;
        }
    }

    for (i = 0; i < SIZE_MAX; ++i) {
        if (array[i] != 0) {
            a[p++] = array[i];
        }
    }

    for (i = 0; i < SIZE_MAX; i++) {
        printf("%d", a[i]);
    }
}

I changed SIZE_MAX to 10, so that it matches the number of elements in the array.

like image 95
Tom Fenech Avatar answered Dec 08 '25 18:12

Tom Fenech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!