I have this bubble sort I need to add a counter to check the
I have this bubble sort. I need to add a counter to check the comparisons. In order words, how often I check one element in the array against another.
 Am I doing it, right? If not, How can I fix it? Thank you
#include <iostream>
 using namespace std;
void bubbleSort(int theArray[], int n)
 {
    int comparisons = 0; //counter is
    bool sorted = false;
    int pass = 1;
    while(!sorted && (pass<n))
    {
        // At this point, theArray[n+1-pass .. n-1] is sorted
        // and all of its entries are > the entries in theAraay[0..n-pass]
        sorted = true;
        for(int index = 0; index < n-pass; index++)
        {
            comparisons++;
            // At this point, all entires in theArrat[0.. index-1]
            // are <= theArray[index]
            int nextIndex = index+1;
            if(theArray[index] > theArray[nextIndex])
            {
                //exchange entries
                swap(theArray[index], theArray[nextIndex]);
                sorted = false; //signel exchange
               
            } // end if
        } //end for
        //asseertion: theArray[0..n-pass-1] < theArray[n-pass]
       pass++;
    }//end while
   cout << \"Number of comparison: \" << comparions;
 }//end bubbleSort;
 void displayArray(int theArray[], int size)
 {
    for(int i=0; i <size; i++ )
    {
        cout<<theArray[i]<<\" \";
    }//end for
 }// end displayArray
int main()
 {
    int data[] = {1};
    //int data1[] = {2, 1};
    //int data2[] ={ 1,2};
    int data3[] = {4, 1, 3, 2, 0, 7};
   cout<<\"The array data contains: \" << endl;
    displayArray(data,1);
    cout<<endl;
    bubbleSort(data, 1); // the int is the size of the
    cout<<endl;
    cout<< \"The array data after sorting: \" << endl;
    displayArray(data,1);
    cout<<endl<<endl;
    cout<<\"The array data3 contains: \" << endl;
    displayArray(data3,6);
    cout<<endl;
    bubbleSort(data3, 6); // the int is the size of the
    cout<<endl;
    cout<< \"The array data3 after sorting: \" << endl;
    displayArray(data3,6);
    cout<<endl;
   int array8a[] = {1, 4, 23, 37, 2, 7,3, 9};
    int array8b[] = {9,7,2, 37, 23, 4, 1, 3};
 }
Solution
The program is perfect to check the number of comparisons occured during bubble sort.
however you have made a mistake in: cout << \"Number of comparison: \" << comparions;
it should be comparisons. Rest assured i could not find any problems with the code or the way to calculate the comparisons done.
please comment for any other clarifications as i believe the question is answered.


