您的位置:首页 > 其它

有两个升序排列的数组A1和A2,给A1开辟的剩余内存有足够空间容纳A1,请实现一个函数,把A2中所有数字插入到A1中,并且是按照升序排列的

2018-02-14 16:06 681 查看
c++代码

#include<iostream>
using namespace std;

void insertArray(int A1[], int A2[], int len1, int len2)
{
int newIndex=((len1--)+(len2--))-1;//先给原值再自减
while (len1 >= 0 && len2 >= 0)
{
if (A1[len1] >= A2[len2])//从后往前
A1[newIndex--] = A1[len1--];
else
A1[newIndex--] = A2[len2--];
}

while (len1 >= 0)//剩余的
A1[newIndex--] = A1[len1--];
while (len2 >= 0)
A1[newIndex--] = A2[len2--];
}

int main()
{
int A1[20] = { 7, 8, 9, 11 };
int A2[4] = { 4, 5, 8, 10 };
int len1 = 4, len2 = 4;

cout << "数组A1中的数为" << endl;
for (int i = 0; i < len1; ++i)
cout << A1[i] << " ";

cout << endl<<"数组A2中的数为" << endl;
for (int i = 0; i < len2; ++i)
cout << A2[i] << " ";
insertArray(A1, A2, len1, len2);
cout << endl << "A2插入A1后新的数组为" << endl;
for (int i = 0; i < len1 + len2; i++)
cout << A1[i] << " ";
cout << endl;

system("pause");
return 0;
}

运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐