题目
Description
已知一个有序顺序表类SortList及main函数的部分代码如下,请完成SortList类的成员函数Insert和DispList,得到对应的运行结果,勿改动main函数。注意:插入函数Insert效率为O(n),不能利用排序算法实现。
//有序表类
template
class SortList{
public:
SortList(){length=0;} //置空表
~SortList(){}
void Insert(T x); //非递减有序表的插入x,使序列仍有序
void DispList(); //输出表
private:
T data[MaxSize]; //存储元素
int length; //顺序表实际长度
};
//构造有序表A:函数声明
template
void CreateSort(SortList &A);
//主函数
int main(){
SortList <int> A; //整型数据表A
//生成一个有序表A
CreateSort(A);
SortList <char> B; //字符型数据表B
CreateSort(B);
A.DispList();
B.DispList();
return 0;
}
//构造有序表A:函数定义
template
void CreateSort(SortList &A){
int i,n;
T x;
cin>>n;
for (i=1;i<=n;i++){
cin>>x;
try{
A.Insert(x);
}
catch(const char *wrong){
cout<<wrong<<endl;
}
}
}
Input
数据输入说明:下列两行输入分别代表创建A表和B表,元素分别为整型和字符型,每行输入中第一个值为元素个数,之后为待插入的各个数据。
5 3 24 23 2 6
4 abnf
Output
输出数据用空格隔开,且结果为元素的有序序列。
Sample Input
5 3 24 23 2 6
4 abnf
Sample Output
The length:5
The elements:
2 3 6 23 24
The length:4
The elements:
a b f n
解决代码
//void CreateSort(SortList <T>& A);
//void SortList<T>::Insert(T x)
//{
// int i;
// for (i = 0; i < length; i++)
// {
// if (data[i] > x)
// {
// for (int j = length; j > i; j--)
// {
// data[j] = data[j - 1];
// }
// break;
//
// }
//
// }
// data[i] = x;
// length++;
//}
#include<bits/stdc++.h>
using namespace std;
// 有序表类
const int MaxSize = 1000;
template <class T>
class SortList {
public:
SortList() { length = 0; } //置空表
~SortList() {}
void Insert(T x); //非递减有序表的插入x,使序列仍有序
void DispList(); //输出表
private:
T data[MaxSize]; //存储元素
int length; //顺序表实际长度
};
template<class T>
void SortList<T>::Insert(T x)
{
int i;
for (i = 0; i < length; i++)
{
if (data[i] > x)
{
for (int j = length; j >i; j--)
{
data[j] = data[j-1];
}
break;
}
}
data[i] = x;
length++;
}
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;
}
//构造有序表A:函数声明
template <class T>
void CreateSort(SortList <T>& A);
//主函数
int main() {
SortList <int> A; //整型数据表A
//生成一个有序表A
CreateSort(A);
SortList <char> B; //字符型数据表B
CreateSort(B);
A.DispList();
B.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 (const char* wrong) {
cout << wrong << endl;
}
}
}
笔记
多种类型数组
将原本主函数外分了一个void CreateSort(SortList & A)函数
用于实现不同数据类型的数组实现
insert代码
void SortList<T>::Insert(T x)
{
int i;
for (i = 0; i < length; i++)
{
if (data[i] > x)
{
for (int j = length; j >i; j--)
{
data[j] = data[j-1];
}
break;
}
}
data[i] = x;
length++;
}