How do I add a counter to a bubble? Sorting to count the number of comparisons?

Considering the following code:

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;
}

      

when i call the function why the output is CountBubbleSort

"0" what is the problem?

+3


source to share


1 answer


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;
}

      



To count the number of comparanas, you just need to add your inner self (on every second loop you do) to your Bubble count at every step of your first loop.

+4


source







All Articles