1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47


//Remove all elements, which is equal to t, in array A
int RemoveElement(int A[], int n, int t)
{
    int i = 0;
    int j = n;

    while(i<j)
    {
        if (A[i] == t)
        {
            //search from back to front, find a element
            //that is not t to change with A[i]
            while(--j > i && A[j] == t);
            //No element in the remain of array is not t,
            //stop searching.
            if(j <= i)
                break;
            else //switch two elements to move t to the back of array
                A[i] = A[j];
        }

        ++i;
    }

    return i;
}

#include <stdio.h>


void printArray(int A[], int n)
{
    for (int i = 0; i < n; ++i)
        printf("%c%d", i==0?'\n':',', A[i]);
}

int main(int argc, char** argv)
{
    int A[] = {1,2,3,3,4,3,3,5,3,3,6,3,3,3,7,3,3,3,3,3,3};
    
    printArray(A,21);
    int n = RemoveElement(A,21,3);
    printArray(A,n);

    return 0;
}
View Program Text


Test Status