2016-03-03 101 views
-4

这是一种在特定条件下合并两个数组的算法。它首先比较两个数组的索引,并且如果arrayP1的索引等于arrayp2的索引,则它将该特定索引存储到答案数组中。 任何一个可以帮助该算法在C++翻译合并排序算法合并两个数组中的第三个条件

#include <iostream> 
#include <cstdlib> 
#include <conio.h> 
using namespace std; 

int main() 
{ 

int sizeofarray=0,i=0 ,j=0, num=0, answers[]={}; 
cout<<"enter the size of array"<<endl; 
cin>>sizeofarray;//take size of array from user 
int array1[sizeofarray]; 
int array2[sizeofarray]; 
cout<<"please enter a sorted array member of Array1"<<endl; 
//input of array element 
for (i=0 ; i<=sizeofarray; i++) 
{ 
cin>>array1[i]; 
} 
system("CLS"); 
cout<<"please enter a sorted array member of Array2"<<endl; 
for (j=0 ; j<=sizeofarray; j++) 
{ 
cin>>array2[j]; 
} 
***strong text***system("CLS"); 
//comparing the array element and storing the similar items to another   array 
while(array1[i]!=NULL && array2[j]!=NULL){ 
if(array1[i]==array2[j]){ 
answer[num++]=array1[i]; 
i++; 
j++; 
} 
else if(array1[i]<array2[j]) 
{ 
i++; 
}else{ 
    j++; 
    } 
i++; 
j++; 
} 
cout<<"The number of common elements"<<num<<endl; 
cout<<"These are the common numbers: "; 
for (int k=0;k<num;k++){ 
cout<<answer[k]<<" "; 
} 
getch(); 
return 0; 

} 
+2

有人也许可以。 –

+0

我也这么认为,看起来不那么难。你试过什么了?包含您的代码 – dmaij

+0

这不是合并,而是相交2个有序集合。你的标题是误导性的。 – knivil

回答

0
#include <iostream> 
#include <cstdlib> 
#include <conio.h> 
using namespace std; 

int main() 
{ 

int sizeofarray=0,i=0 ,j=0, num=0, answers[]={}; 
cout<<"enter the size of array"<<endl; 
cin>>sizeofarray;//take size of array from user 
int array1[sizeofarray]; 
int array2[sizeofarray]; 
cout<<"please enter a sorted array member of Array1"<<endl; 
//input of array element 
for (i=0 ; i<=sizeofarray; i++) 
{ 
    cin>>array1[i]; 
} 
system("CLS"); 
cout<<"please enter a sorted array member of Array2"<<endl; 
for (j=0 ; j<=sizeofarray; j++) 
{ 
    cin>>array2[j]; 
} 
system("CLS"); 
//comparing the array element and storing the similar items to another array 
while(array1[i]!=NULL && array2[j]!=NULL){ 
    if(array1[i]==array2[j]){ 
    answer[num++]=array1[i]; 
    i++; 
    j++; 
    } 
    else if(array1[i]<array2[j]) 
{ 
i++; 
}else{ 
j++; 
    } 
i++; 
j++; 
} 
cout<<"The number of common elements"<<num<<endl; 
cout<<"These are the common numbers: "; 
for (int k=0;k<num;k++){ 
    cout<<answer[k]<<" "; 
} 
getch(); 
return 0; 

}