c语言实现集合的交并差运算
时间: 2023-07-13 21:39:40 浏览: 80
集合的交、并、差运算可以通过数组来实现,具体实现如下:
```c
#include <stdio.h>
void intersection(int a[], int b[], int c[], int m, int n) {
int i, j, k;
i = j = k = 0;
while (i < m && j < n) {
if (a[i] < b[j]) {
i++;
} else if (b[j] < a[i]) {
j++;
} else {
c[k] = a[i];
i++;
j++;
k++;
}
}
}
void union_set(int a[], int b[], int c[], int m, int n) {
int i, j, k;
i = j = k = 0;
while (i < m && j < n) {
if (a[i] < b[j]) {
c[k] = a[i];
i++;
k++;
} else if (b[j] < a[i]) {
c[k] = b[j];
j++;
k++;
} else {
c[k] = a[i];
i++;
j++;
k++;
}
}
while (i < m) {
c[k] = a[i];
i++;
k++;
}
while (j < n) {
c[k] = b[j];
j++;
k++;
}
}
void difference(int a[], int b[], int c[], int m, int n) {
int i, j, k;
i = j = k = 0;
while (i < m && j < n) {
if (a[i] < b[j]) {
c[k] = a[i];
i++;
k++;
} else if (b[j] < a[i]) {
j++;
} else {
i++;
j++;
}
}
while (i < m) {
c[k] = a[i];
i++;
k++;
}
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int b[] = {3, 4, 5, 6, 7, 8};
int m = sizeof(a) / sizeof(a[0]);
int n = sizeof(b) / sizeof(b[0]);
int c[m + n], d[m + n], e[m + n];
intersection(a, b, c, m, n);
union_set(a, b, d, m, n);
difference(a, b, e, m, n);
printf("A ∩ B = { ");
for (int i = 0; i < sizeof(c) / sizeof(c[0]); i++) {
if (c[i] != 0) {
printf("%d ", c[i]);
}
}
printf("}\n");
printf("A ∪ B = { ");
for (int i = 0; i < sizeof(d) / sizeof(d[0]); i++) {
if (d[i] != 0) {
printf("%d ", d[i]);
}
}
printf("}\n");
printf("A - B = { ");
for (int i = 0; i < sizeof(e) / sizeof(e[0]); i++) {
if (e[i] != 0) {
printf("%d ", e[i]);
}
}
printf("}\n");
return 0;
}
```
输出结果为:
```
A ∩ B = { 3 4 5 }
A ∪ B = { 1 2 3 4 5 6 7 8 }
A - B = { 1 2 }
```
阅读全文