在有效地计算数组中第二个元素较少的对时,我哪里出错了?

Where am I going wrong in counting pairs where second element is less in array efficiently?

给定一个元素数组,return一个值数组,表示有多少元素大于给定数组中的值?

两个循环的蛮力方法在这里很明显,O(n^2) 但我想做得更好。因此,我尝试使用修改合并排序。我做了一个节点,它有两个成员。实际值,以及它小于(计数)的元素数。计数初始化为零。我的代码如下:

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include <stack>
#include <queue>
#include <climits>
#include <set>
#include <cstring>
#include <cstdio>
#include <cmath>

using namespace std;


class node 
{
public:
    int val;
    int count;
};

void merge(node *temp,int, int , int );
void mergesort(node *temp, int low, int high)
{
    int mid;
    if (low < high)
    {
        mid=(low+high)/2;
        mergesort(temp,low,mid);
        mergesort(temp,mid+1,high);
        merge(temp,low,high,mid);
    }
    return;
}
void merge(node *temp, int low, int high, int mid)
{
    int i, j, k;
    node c[50];
    i = low;
    k = low;
    j = mid + 1;
    while (i <= mid && j <= high)
    {
        if (temp[i].val < temp[j].val)
        {
            c[k] = temp[i];
            k++;
            i++;
            c[k].count = c[k].count + high-j+1;   // only change which should calculate
        }
        else
        {
            c[k] = temp[j];
            k++;
            j++;
        }
    }
    while (i <= mid)
    {
        c[k] = temp[i];
        k++;
        i++;
    }
    while (j <= high)
    {
        c[k] = temp[j];
        k++;
        j++;
    }
    for (i = low; i <= high; i++)
    {
        temp[i] = c[i];
    }
}
int main()
{
    node a[20];
    node b[20];
    int i;
    cout<<"enter  the elements\n";
    for (i = 0; i < 7; i++)
    {
        cin>>a[i].val;
        a[i].count = 0;
    }
    mergesort(a, 0, 6);
    cout<<"sorted array\n";
    for (i = 0; i < 7; i++)
    {
        cout<<a[i].val<<" "<<a[i].count<<"\n";
    }
    return 0;
}  

但是,上面的输出,0 作为所有元素的计数值,但是,它正确地对元素进行了排序。例如,输入为

3 4 5 9 2 1 3  

O/P结果是,

1 0
2 0
3 0
3 0
4 0
5 0
9 0

为什么计数为0?

以下跳转到眼睛:

c[k] = temp[i];
k++;
i++;
c[k].count = c[k].count + high-j+1;   // only change which should calculate

为什么值插入到一个元素中,然后计数在下一个中更新?我用我的魔眼看到增加的计数在下一次迭代中被零覆盖,给你你的结果。

重写为:

c[k] = temp[i];
c[k].count = c[k].count + high-j+1;   // only change which should calculate
k++;
i++;

可能会有帮助。