考虑以下代码:
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”,问题是什么?
答案 0 :(得分:4)
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。