template <class ElemType> void Show(const ElemType &e) // 操作结果: 显示数据元素 { cout << setw(2) << e << " "; } template<class ElemType> void ShowRunK(LinkList<ElemType> &la, int k) // 操作结果: 显示链表la的各数据元素值 { ElemType e; cout << "第" << setw(2) << k << "趟排序结果:"; la.Traverse(Show); cout << endl; } template <class ElemType> void SelectSort(LinkList<ElemType> &la) // 操作结果: 以带头结点的单链表为存储结构实现简单选择排序 { ElemType t; ElemType check; ElemType emin; int min; for (int i = 1; i < la.Length(); i++) { la.GetElem(i,emin); min = i; for (int j = i + 1; j <= la.Length(); j++) { la.GetElem(j, check); if (check < emin); { min = j; la.GetElem(j, emin); } } la.GetElem(i, t); la.SetElem(i, emin); la.SetElem(min, t); ShowRunK(la, i); } }改正并简化此代码
时间: 2024-01-28 08:03:09 浏览: 28
template <class ElemType>
void SelectSort(LinkList<ElemType> &la)
{
ElemType emin;
int min;
for (int i = 1; i < la.Length(); i++)
{
la.GetElem(i, emin);
min = i;
for (int j = i + 1; j <= la.Length(); j++)
{
ElemType check;
la.GetElem(j, check);
if (check < emin)
{
min = j;
emin = check;
}
}
la.SetElem(i, emin);
}
}
相关问题
template <class ElemType> void StatDegree(const AdjListDirGraph<ElemType> &g, int *Degree) // 操作结果:统计图g各顶点的度 { }
这段代码实现了统计有向图中每个顶点的度数的功能。其中模板类`AdjListDirGraph`表示邻接表实现的有向图,`ElemType`表示顶点的数据类型。函数的参数`g`为传入的有向图对象,`*Degree`为指向存储度数结果的数组的指针。
具体实现可以按照以下步骤:
1. 获取有向图中所有的顶点,可以通过`g.GetVertex() `方法实现。该方法返回一个`vector`类型的顶点数组。
2. 对于每个顶点,遍历其所有的出边(即该顶点连向其他顶点的边),并统计出边的个数。可以通过邻接表中每个顶点对应的链表来实现。
3. 将每个顶点的出边数作为该顶点的出度,并将结果存储在`*Degree`数组中。
完整代码如下:
```c++
template <class ElemType>
void StatDegree(const AdjListDirGraph<ElemType> &g, int *Degree) {
vector<Vertex<ElemType>> vertexList = g.GetVertex();
for (int i = 0; i < vertexList.size(); i++) {
int outDegree = 0;
ArcNode *p = vertexList[i].firstArc;
while (p != NULL) {
outDegree++;
p = p->nextArc;
}
Degree[i] = outDegree;
}
}
```
template <class ElemType> bool IsBBTHelp(BinTreeNode<ElemType> *r,int &h) // 操作结果: 判断以r为根的二叉排序树是否为平衡二叉树, h表示二叉排序树的深度 { } template <class ElemType, class KeyType> bool IsBBT(const BinarySortTree<ElemType, KeyType> &t) // 操作结果: 判断二叉排序树是否为平衡二叉树 { int h; return IsBBTHelp((BinTreeNode<ElemType> *)t.GetRoot(), h); }
这是一个判断二叉排序树是否为平衡二叉树的函数模板。其中,IsBBTHelp是一个递归函数,用于计算以r为根节点的二叉排序树的深度,并判断其是否为平衡二叉树。而IsBBT则是调用IsBBTHelp函数来判断整个二叉排序树是否为平衡二叉树。
具体来说,IsBBTHelp函数的实现如下:
```cpp
template <class ElemType>
bool IsBBTHelp(BinTreeNode<ElemType> *r, int &h) {
if (r == nullptr) { // 空树是平衡二叉树
h = 0;
return true;
}
int lh, rh; // 左右子树的深度
if (IsBBTHelp(r->leftChild, lh) && IsBBTHelp(r->rightChild, rh)) { // 分别判断左右子树是否平衡
if (abs(lh - rh) <= 1) { // 左右子树深度差不超过1,则以r为根的二叉排序树为平衡二叉树
h = max(lh, rh) + 1; // 更新以r为根的二叉排序树的深度
return true;
}
}
return false; // 否则不是平衡二叉树
}
```
而IsBBT函数的实现就非常简单了,只需要调用IsBBTHelp函数即可:
```cpp
template <class ElemType, class KeyType>
bool IsBBT(const BinarySortTree<ElemType, KeyType> &t) {
int h;
return IsBBTHelp((BinTreeNode<ElemType> *)t.GetRoot(), h);
}
```
其中,t.GetRoot()返回二叉排序树的根节点,强制转换为BinTreeNode<ElemType>*类型后传给IsBBTHelp函数。最终返回的结果就是整个二叉排序树是否为平衡二叉树。