MrEmper
MrEmper

Reputation: 235

C - delete element from array and reorganise

Given this array:

int a[] = {5, 8, 5, 6, 9, 5};

Would it be possible to remove all ints which equals 5 and move the rest the front of the array?

So that after the removal the array would look like this:

int a[] = {8, 6, 9, 0, 0, 0}

I don't know if by removing a element it becomes a 0 or a NULL?

Thanks!

Upvotes: 0

Views: 2128

Answers (4)

IBraheem.B
IBraheem.B

Reputation: 21

You can do it with two iterations over the array, first iteration two to turn the element you want to delete, second iteration to separate zeros from non-zeros.

    int a[] = {5, 8, 5, 6, 9, 5};
    int n = 6;
    for(int i = 0 ; i < n ; i++ ) {
        if(a[i] == 5 ) {
            a[i] = 0;
        }
    }
    int* zero = a;

    int* nonZero = a;
    int j = 0;

    while(j < n) {

        while(*zero != 0) {
            zero++;
        }       

        while(*nonZero == 0) {
            nonZero++;
            j++;
        }
        if(zero < nonZero) {
            *zero = *nonZero;
            *nonZero = 0;
        }
        j++;
    }

Upvotes: 2

user4836681
user4836681

Reputation:

your array is not dynamic so you just can't reduce its size after its been allocated.setting the value zero might solve the problem in your case.

Upvotes: 0

user9714918
user9714918

Reputation:

It is been awhile that i have programmed in C but it is posibble.

This is just a pseudo code, but you just need to change it to way of C programming.

int a[] = {5, 8, 5, 6, 9, 5};
int b[] = {5, 8, 5, 6, 9, 5}; // copy of array a to hold temp
for(int i = 0; i < Size of array; i++ ){
  for(int j = i; j < Size of array; j++ ){
    if(b[j] != 5){
       a[i] = b[j];
       a[j] = b[i];
       break;
    }
  }
}

It will be like (▼: Target to swap, F: Finished, X: Not a targe to swap, N: Not processed):

▼, ▼, N, N, N, N

5, 8, 5, 6, 9, 5

F, ▼, X, ▼, N, N

8, 5, 5, 6, 9, 5

F, F, ▼, X, ▼, N

8, 6, 5, 5, 9, 5

Result: 8, 6, 9, 5, 5, 5

And remove 5s, it is quite different depends what you mean. If you do not change size of array then they can be 0 or undefined(null). So I think it differs by how you program the function that returns array.

Upvotes: 0

Your array is statically allocated, so always has the same size and deleted elements have the 0 value (according how you define the deleted values).

This link can help you and explains about how to delete element from array.

Upvotes: 1

Related Questions