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

标签 c++ arrays recursion mergesort

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

两个循环的蛮力方法在这里很明显,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++;

可能会有帮助。

关于c++ - 在有效地计算数组中第二个元素较少的对时,我哪里出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33562722/

相关文章:

android - 为什么 opencv 的默认颜色空间在 android 中不同?

c++ - C++中命名空间指令的正确使用方法

python-3.x - 使用python递归返回列表列表

java - 递归地打印出数组中等于给定总和的所有子集

c++ - 程序在Turbo C中运行良好,但在MSVC中失败,出现未处理的异常

c++ - C++继承和相同的函数名称

php - IN array in where 子句 mysql php pdo

arrays - 设置名词集时,如何在 Bash 中将 "-@-expand ("${array[@]}") 可能为空数组?

c++ - sizeof 函数在函数中不起作用

javascript - Vuejs : Dynamic Recursive components (Tree Like Structure)