Bubble sorts the total number of comparisons and swaps.

I have this code for sorting bubbles in C ++. First, it generates random numbers and puts them inside the array. After that, I call my bubbleSort function, which does the sorting. Everything is working fine. However, I was curious how I can find a series of complete comparisons and the exchange of numbers that the bubble creates? I created an integer CountBubbleSort for comparison. However, I am not sure in which part of my code I should increase it. I thought to add it after the second cycle, inside the first. I hope you understand what I mean. Is this right or wrong? The number of comparisons determines this formula n * (n-1)) / 2. And with swaps it's 3 * (n-1). But how can I implement it in my code? Thanks for helping the guys.

void swap(double *xp, double *yp)
{
    double temp = *xp;
    *xp = *yp;
    *yp = temp;
}

double *Data;
double* A;
double n, temp;

void generate(int _n, const char *_file);
void read(const char *_file);   
void printArray(double arr[], int n); 
void bubbleSort(double arr[], int n);

int main()
{
    int m;
    int CountBubbleSort = 0;

    srand(time(NULL));
    cout << "Amount of random numbers you want: ";
    cin >> m;
    cout << "Generating random data ..." << endl;
    generate(m, "duom.txt");
    cout << "Reading data" << endl;
    read("duom.txt");
    A = new double[n];

    for (int i = 0; i < n; i++) {
        A[i] = Data[i];
    }

    cout << "Randomly generated array" << endl;
    printArray(A, n);

    // Bubble Sort
    bubbleSort(A, n);

    cout << "Array after bubble sort" << endl;
    printArray(A, n);

    return 0;
}

void bubbleSort(double arr[], int n)
{
    bool swapped;
    for (int i = 0; i < n - 1; i++)
    {
        swapped = false;
        for (int j = 0; j < n - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                swap(&arr[j], &arr[j + 1]);
                swapped = true;
            }
        }
        // Should I add CountBubbleSort += i here or not?
        if (swapped == false)
            break;
    }
}

void printArray(double arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << A[i] << endl;
    }
}
+4
2

:

  • if
  • if

int& , :

void bubbleSortCounted(double arr[], int n, int& countComparisons, int& countSwaps);

, , :

countComparisons++;
if (arr[j] > arr[j + 1])
{
    countSwaps++;
    swap(&arr[j], &arr[j + 1]);
    swapped = true;
}

main() :

int cmp = 0, swp = 0;
bubbleSort(A, n, cmp, swp);
std::cout << cmp << " comparisons, " << swp << " swaps" << std::endl;
+3

, , ? CountBubbleSort . , .

bubbleSort() , , , , .

+1

Source: https://habr.com/ru/post/1689909/


All Articles