查找c++数组中的最频繁值和中位数

Find most frequent and median values in array C++

本文关键字:中位数 c++ 数组 查找      更新时间:2023-10-16

我想通过使用c++找到给定数组的最频繁值和中位数。我假设我有一个浮点数组,如

float *LRArr=new LRArr[1000];

数组由随机浮点数填充。

std::default_random_engine generator;
generator.seed( rd() );
std::uniform_real_distribution<> distribution(0, 10);
for(int j=0;j<1000;j++)
{
    LRArr[j]=distribution(generator)
}

现在我想要得到数组中出现频率最高的值。但这需要很多时间。你能告诉我用C或c++实现它的更快的方法吗?我假设我有LRArr,如

LRArr={0.1,1.2,6.5,6.5,4.5,6.5}
==>output is: 6.5 and median 5.5

这是我的方式:

float getMostFreq(float* LRArr;int sizeLRArr)
{
int count = 1;
int currentIndex = 0;
   for (int i = 1; i < sizeLRArr; i++)
   {
    if (LRArr[i] == LRArr[currentIndex])
        count++;
    else
        count--;
    if (count == 0)
    {
        currentIndex = i;
        count = 1;
    }
  }
  mostFreq = LRArr[currentIndex];
  return mostFreq;
} 

计算数组中float值出现频率的一种方法是计算直方图并对其排序。但是你应该考虑到你的值的范围应该被定义。这样,准确率取决于直方图箱的数量:

#include <algorithm>
#define histogramCount 10000
#define upperRange 1000
#define lowerRange 0
class histogram_data
{
public:
  int frequency;
  int index;
};
bool SortPredicate(const histogram_data& d1, const histogram_data& d2)
{
    return d1.frequency> d2.frequency;
}

void computeHistogram(float * array, int len)
{
   std::vector<histogram_data> histogram;
   for(int i=0;i<histogramCount;i++)
   {
       histogram_data hdata;
       hdata.frequency=0;
       hdata.index=i;
       histogram.push_back(hdata);
   }

   for(int i=0;i<len;i++)
   {
       histogram[(array[i]/(upperRange-lowerRange))*(histogramCount-1)].frequency++;
   }
   //sorting the histogram in descending order
    std::sort(histogram.begin(),histogram.end(),SortPredicate);
}

现在数值的频率按降序存储在直方图中。因此,最常见的值可以通过以下方式获得:

float mostFrequent = ((float)histogram[0].index/(float)(histogramCount-1))*(upperRange-lowerRange);