gpt4 book ai didi

c++ - 如何在冒泡排序中添加一个计数器来统计数字比较?

转载 作者:太空狗 更新时间:2023-10-29 20:57:36 24 4
gpt4 key购买 nike

考虑以下代码:

int CountBubbleSort=0;
template <typename Comparable>
void bubbleSort(vector<Comparable*> &v)
{
bool sorted = false;
for(int pass = 1; pass < v.size() && !sorted; pass++)
{
sorted = true;
for(int i = 0; i < v.size() - pass; i++)
{
if(*v[i + 1] < *v[i])
{
swap(v, i, i + 1);
CountBubbleSort++;
sorted = false;

}
}
}
cout<<"bubbleSort comparison is "<<CountBubbleSort<<endl;
}

当我调用该函数时,为什么 CountBubbleSort 的输出是“0”,这是什么问题?

最佳答案

void bubbleSort(vector<Comparable*> &v)
{
bool sorted = false;
for(int pass = 1; pass < v.size() && !sorted; pass++)
{
sorted = true;
int i;
for(i = 0; i < v.size() - pass; i++)
{
if(*v[i + 1] < *v[i])
{
swap(v, i, i + 1);
sorted = false;

}
}
CountBubbleSort += i;
}
cout<<"bubbleSort comparison is "<<CountBubbleSort<<endl;
}

要计算比较的次数,您只需在第一个循环的每一轮将内部 i(在每个第二个循环中进行比较)添加到您的 countBubble 中。

关于c++ - 如何在冒泡排序中添加一个计数器来统计数字比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30048546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com