1003: 顺序表(3)
Description
请在上题SortList类的基础上添加成员函数Merge,实现两个有序表的合并。部分代码已经给出,请勿改动。注意:合并算法效率要求为O(m+n),不能借助排序算法实现。
//有序表类
template <class T>
class SortList{
public:
SortList(){length=0;}
~SortList(){}
void Insert(T x); //有序表的插入,使序列仍有序
void DispList(); //输出表
/*成员函数Merge实现两个有序表的合并,使序列仍有序,
将A表和B表合并到当前类中,要求:A表,B表的元素保持不变*/
void Merge(SortList <T> &A,SortList <T> &B);
private:
T data[MaxSize]; //存储元素
int length; //顺序表实际长度
};
//构造有序表A:函数声明
template <class T>
void CreateSort(SortList <T> &A);
int main(){
SortList <int> A,B,C;
//生成一个有序表A
CreateSort(A);
//生成一个有序表B
CreateSort(B);
try{
C.Merge(A,B);//合并A,B表为C表
}
catch(const char* wrong){
cout << wrong; //如失败提示失败信息
}
A.DispList();
B.DispList();
C.DispList(); //显示合并后的结果
return 0;
}
//构造有序表A:函数定义
template <class T>
void CreateSort(SortList <T> &A){
int i,n;
T x;
cin>>n;
for (i=1;i<=n;i++){
cin>>x;
try{
A.Insert(x);
}
catch(char *wrong){
cout<<wrong<<endl;
}
}
}
Input
数据输入格式:第一个为所创建表的元素个数,之后是各个元素值,例如,下例输入,两个表的元素个数分别为5,6。
5 4 24 2 42 3
6 78 36 34 24 64 43
Output
Sample Input
5 4 24 2 42 3
6 78 36 34 24 64 43
Sample Output
The length:5
The elements:
2 3 4 24 42
The length:6
The elements:
24 34 36 43 64 78
The length:11
The elements:
2 3 4 24 24 34 36 42 43 64 78
#include<iostream>
using namespace std;
const int MaxSize = 100;
template<class T>
class SortList {
private:
T data[MaxSize]; //存储元素
int length; //顺序表实际长度
public:
SortList() { length = 0; }
~SortList() {}
void Insert(T x); //有序表的插入,使序列仍有序
/*成员函数Merge实现两个有序表的合并,使序列仍有序,
将A表和B表合并到当前类中,要求:A表,B表的元素保持不变*/
void Merge(SortList<T> &A, SortList<T> &B);
void DispList(); //输出表
};
template<class T>
void SortList<T>::DispList() {
cout << "The length:" << length << endl;
cout << "The elements:" << endl;
for (int i = 0; i < length; i++) {
cout << data[i] << " ";
}
cout << endl;
}
template<class T>
void SortList<T>::Insert(T x) {
int i;
for (i = 0; i < length; i++) {
if (data[i] > x)break;
}
for (int j = length; j > i; j--) {
data[j] = data[j - 1];
}
data[i] = x;
length++;
}
template<class T>
void SortList<T>::Merge(SortList<T> &A, SortList<T> &B) {
int ai = 0, bi = 0;
while (ai < A.length && bi < B.length) {
if (A.data[ai] < B.data[bi]) {
data[length++] = A.data[ai++];
} else {
data[length++] = B.data[bi++];
}
}
while (ai < A.length) data[length++] = A.data[ai++];
while (bi < B.length) data[length++] = B.data[bi++];
}
///构造有序表A:函数定义
template<class T>
void CreateSort(SortList<T> &A) {
int i, n;
T x;
cin >> n;
for (i = 1; i <= n; i++) {
cin >> x;
try {
A.Insert(x);
}
catch (char *wrong) {
cout << wrong << endl;
}
}
}
//构造有序表A:函数声明
template<class T>
void CreateSort(SortList<T> &A);
int main() {
SortList<int> A, B, C;
//生成一个有序表A
CreateSort(A);
//生成一个有序表B
CreateSort(B);
try {
C.Merge(A, B);//合并A,B表为C表
}
catch (const char *wrong) {
cout << wrong; //如失败提示失败信息
}
A.DispList();
B.DispList();
C.DispList(); //显示合并后的结果
return 0;
}