C 程序用于对两个数组执行交集运算


交集运算

如果数组 1 = {1,2,3,4,6}

 数组 2 = {1,2,5,6,7}

那么,数组 1 和数组 2 的交集是

Array1 ^ array 2 = {1,2,3,4,6} ^ {1,2,5,6,7}
                 = {1,2,6}

相同元素构成的集合被称为交集。

交集的逻辑如下 -

k=0;
for(i=0;i<size1;i++){
   for(j=0;j<size2;j++){
      if(a[i]==b[j]){
         intersection[k]=a[i];
         k++;
      }
   }
}

程序

以下是用于对两个数组执行交集运算的 C 程序 -

 在线演示

#include<stdio.h>
int removerepeated(int size,int a[]);
void sort(int size,int a[]);
main(){
   int i,size1,size2,size,j=0,k,intersectionsize;
   printf("Enter size of an array1
");    scanf("%d",&size1);    printf("Enter size of an array2
");    scanf("%d",&size2);    int a[size1],b[size2],uni[size1+size2];    if(size1<size2){       intersectionsize=size1;    }else if(size1>size2){       intersectionsize=size2;    }else{       intersectionsize=size1;    }    int intersection[intersectionsize];    printf("Enter numbers for array 1
");    for(i=0;i<size1;i++){       scanf("%d",&a[i]);    }    printf("Enter numbers for array 2
");    for(i=0;i<size2;i++){       scanf("%d",&b[i]);    }    //Intersection starts    k=0;    for(i=0;i<size1;i++){       for(j=0;j<size2;j++){          if(a[i]==b[j]){             intersection[k]=a[i];             k++;          }       }    }    //Sorting    sort(k,intersection);    //Removing    size=removerepeated(k,intersection);    printf("Array after intersection
");    if(size>0){       for(i=0;i<size;i++){          printf("%d
",intersection[i]);       }    }else{       printf("No intersection
");    } } int removerepeated(int size,int a[]){    int i,j,k;    for(i=0;i<size;i++){       for(j=i+1;j<size;){          if(a[i]==a[j]){             for(k=j;k<size;k++){                a[k]=a[k+1];             }             size--;          }else{             j++;          }       }    }    return(size); } void sort(int size,int a[]){    int i,j,temp;    for(i=0;i<size;i++){       for(j=i+1;j<size;j++){          if(a[i]>a[j]){             temp=a[i];             a[i]=a[j];             a[j]=temp;          }       }    } }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

当执行上述程序时,它会产生以下结果 -

Enter size of an array1
5
Enter size of an array2
2
Enter numbers for array 1
4
5
6
7
8
Enter numbers for array 2
4
1
Array after intersection
4

更新于: 26-Mar-2021

8K+ 次观看

开启你的 职业生涯

完成课程并获得认证

开始使用
广告