题目
对两个有序数组进行合并:设有如下数组A、B,并假设两个数组的元素都已经有序(从大到小降序排列)。编程序,合并A、B数组形成一个新的数组C,并使C的元素仍有序(从大到小降序排列)。
int A[10]={123,88,86,86,33,15,7,0,-1,-3};
int B[10]={86,69,51,50,27,19,15,12,5,2};
设计思想
本题首先要合并两个已知数组,数组A和B均含有10各元素,则需定义一个含有20个元素的数组C,即数组A、B合并后形成的新数组,该数组里的元素则有A、B两个数组里的元素组成。
接着题中要求我们给数组中的各元素按从大到小的顺序排列并输出,所以,我们需要编写一个给数组中元素排序的函数,在这个函数中,我们利用for循环以及值传递等方法来实现元素的排序。
设计表示
源代码
#include "stdafx.h"
#include <iostream>
using namespace std;
void bubble(int *a, int n) //定义两个参数:数组首地址与数组大小
{
int i, j, temp;
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++) //套用两个for循环从而实现循环“扫描”
{
if (a[i] < a[j]) //值传递
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (i = 0; i < n; i++)
{
cout << a[i]<<" ";
}
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int A[10] = { 123, 88, 86, 86, 33, 15, 7, 0, -1, -3 };
int B[10] = { 86, 69, 51, 50, 27, 19, 15, 12, 5, 2 };
int C[20];
int i = 0;
for (int i = 0; i < 20; i++)
{
if (i < 10)
{
C[i] = A[i];
}
else
{
C[i] = B[i - 10];
}
} //数组A、B的合并
cout << "C[A&B] is:" << endl;
bubble(C,20);
return 0;
}