如何将计数器添加到冒泡中排序以计算数字比较?

时间:2015-05-05 09:03:24

标签: c++ counter

考虑以下代码:

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”,问题是什么?

1 个答案:

答案 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。