构造一个exchangeMax()函数,负责交换两个数组中格子元素的最大值,且保持交换元素后所有元素的位置不变。方法是保存最大值下标,最后直接交换即可。
#include <stdio.h>
#include <stdlib.h>
void exchangeMax(int *arr1,int *arr2,int n1,int n2);
int main()
{
int myarr1[5]={4,1,24,55,-18};
int myarr2[8]={32,11,15,-43,21,31,19,26};
int i=0;
printf("old myarr1[5]\n");
for(i=0;i<5;i++)
printf("%3d",myarr1[i]);
printf("\nnew myarr2[8]\n");
for(i=0;i<8;i++)
printf("%3d",myarr2[i]);
printf("\n");
exchangeMax(myarr1,myarr2,5,8); //5和8代表两数组长度
printf("new myarr1[5]\n");
for(i=0;i<5;i++)
printf("%3d",myarr1[i]);
printf("\n new myarr2[8]:\n");
for(i=0;i<8;i++) //
printf("%3d",myarr2[i]);
printf("\n");
system("pause");
return 0;
}
void exchangeMax(int *arr1,int *arr2,int n1,int n2)
{
int tempt;
int max1=0,max2=0;
int i;
for(i=1;i<n1;i++) //找数组1的最大值
{
if(arr1[max1]<arr1[i])
max1=i;
}
for(i=1;i<n2;i++) //找数组2的最大值
{
if(arr2[max2]<arr2[i])
max2=i;
}
//交换最大值
tempt=arr1[max1];
arr1[max1]=arr2[max2];
arr2[max2]=tempt;
}