简体   繁体   中英

How to count comparisons and swaps(inversions) in merge sort? [C++]

I have working code for merge sorting, but I don't know how to count comparisons and swaps(inversions). Any help would be appreciated!

#include<iostream>

using namespace std;

int comparisons = 0;
int moves = 0;

void merge(int arr[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;

    int* L = new int[n1];
    int* R = new int[n2];

    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];

    i = 0;
    j = 0;
    k = l;
    while (i < n1 && j < n2)
    {
        if (L[i] <= R[j])
        {
            arr[k] = L[i];
            i++;
        }
        else
        {
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    while (i < n1)
    {
        arr[k] = L[i];
        i++;
        k++;
    }

    while (j < n2)
    {
        arr[k] = R[j];
        j++;
        k++;
    }
}

void mergeSort(int arr[], int l, int r)
{
    if (l < r)
    {
        int m = l + (r - l) / 2;

        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}

int main()
{
    int size;
    cout << "Enter size: " << endl;
    cin >> size;

    int* arr = new int[size];

    for (int i = 0; i < size; i++) {
        arr[i] = rand() % 100;
    }

    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }

    cout << endl << endl;

    mergeSort(arr, 0, size - 1);

    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }

    cout << endl;

    system("pause");
    return 0;
}

The number of iterations of the while (i < n1 && j < n2) loop is the number of comparisons. You could simply add a counter and count the number of times that loop executes.

You can't really count the number of swaps as your current implementation doesn't actually perform any swaps. You should first rewrite your algorithm to use swaps and then count that. As a rough approximation, every assignment to the array arr roughly corresponds to a swap. I would simply count the number of those.

As an aside, your code has a lot of memory leaks. You must have a corresponding delete [] for every allocation. I would highly recommend using std::vector instead to help avoid bugs like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM