用C++实现2个数组的交集 和并集的函数,交集和并集按照从小到大的顺序输出。
时间: 2023-09-14 13:02:35 浏览: 81
```c
#include <stdio.h>
// 计算数组的长度
int length(int arr[]) {
return sizeof(arr) / sizeof(arr[0]);
}
// 升序排序数组
void sort(int arr[], int len) {
int temp;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
// 数组交集函数
void intersection(int arr1[], int len1, int arr2[], int len2) {
sort(arr1, len1);
sort(arr2, len2);
int i = 0, j = 0;
while (i < len1 && j < len2) {
if (arr1[i] == arr2[j]) {
printf("%d ", arr1[i]);
i++;
j++;
} else if (arr1[i] < arr2[j]) {
i++;
} else {
j++;
}
}
}
// 数组并集函数
void unionSet(int arr1[], int len1, int arr2[], int len2) {
sort(arr1, len1);
sort(arr2, len2);
int i = 0, j = 0;
while (i < len1 && j < len2) {
if (arr1[i] == arr2[j]) {
printf("%d ", arr1[i]);
i++;
j++;
} else if (arr1[i] < arr2[j]) {
printf("%d ", arr1[i]);
i++;
} else {
printf("%d ", arr2[j]);
j++;
}
}
while (i < len1) {
printf("%d ", arr1[i]);
i++;
}
while (j < len2) {
printf("%d ", arr2[j]);
j++;
}
}
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 4, 5, 6, 7};
int len1 = length(arr1);
int len2 = length(arr2);
printf("数组交集为:");
intersection(arr1, len1, arr2, len2);
printf("\n数组并集为:");
unionSet(arr1, len1, arr2, len2);
return 0;
}
```
阅读全文