如何使用合并排序来计算大量输入的求反数

时间:2019-09-27 03:24:27

标签: c++ algorithm mergesort divide-and-conquer

我能够计算少量输入的求逆。我应该进行哪些更改才能计算100000个输入的反转次数。

#include<iostream>

using namespace std;

int _mergeSort(int arr[], int temp[], int left, int right);
int merge(int arr[], int temp[], int left, int mid, int right);

int mergeSort(int arr[], int array_size)
{
    int temp[array_size];
    return _mergeSort(arr, temp, 0, array_size - 1);
}

int _mergeSort(int arr[], int temp[], int left, int right)
{
    int mid, inv_count = 0;

    if (right > left)
    {
        /*Divide the array into two parts
         and call _mergeSortAndCountInv()
         for each of the parts*/

        mid = (left + right) / 2;

        /*Inversion count will be sum of inversions in left-part
         right-part as well as number of inversions while merging */

        inv_count = _mergeSort(arr, temp, left, mid); // counting inversions in the left part
        inv_count += _mergeSort(arr, temp, mid + 1, right); //counting inversions in the right part
        inv_count += merge(arr, temp, left, mid + 1, right);
    }
    return inv_count;
}

int merge(int arr[], int temp[], int left, int mid, int right)
{

    int i, j, k;
    int inv_count = 0;

    i = left; // i is the index for left subarray
    j = mid; // j is the index for right subarray
    k = right; // k is the index for resultant merged subarray

    while (i <= (mid - 1) && j <= right)
    {
        if (arr[i] < arr[j])
            temp[k++] = arr[i++];
        else
        {
            temp[k++] = arr[j++];
            inv_count = inv_count + (mid - i);
        }
    }

    // copying the remaining parts of the left subarray to temp (if any)
    while (i <= (mid - 1))
        temp[k++] = arr[i++];

    // copying the remaining parts of the left subarray to temp (if any)
    while (j <= right)
        temp[k++] = arr[j++];

    // copying back the merged elements to oroginal array ;
    for (i = left; i <= right; i++)
    {
        arr[i] = temp[i];
    }

    return inv_count;
}

int main()
{
    int arr[] = { 5, 7, 2, 3, 9, 1 };

    int n = sizeof(arr) / sizeof(arr[0]);

    int ans = mergeSort(arr, n);
    cout << "Number of inversions are" << "\n" << ans;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

  

k =正确; // k是结果合并子数组的索引

我想这行应该有个问题

  

k = left;

所以问题出在排序算法上。
合并排序的时间复杂度为 Nlog(N),而您添加的只是一行代码

        inv_count = inv_count + (mid - i);
恒定复杂度的

因此,它不会改变算法的整体复杂度。即使输入 100000 ,对数组中的求反数进行计数也不会有任何问题。