考虑到我们有一个大小为n的数组,我们必须使用计数排序技术找到中位数和众数。当阵列元素在有限范围内时,此技术很有用。假设元素为{1、1、1、2、7、1},则模式为1,中位数为1.5。让我们看看什么是中位数,什么是模式-
中位数是数字排序列表中的中间数字
模式是列表中出现次数最多的元素
要获得中位数和众数,我们必须遵循以下步骤:
假设输入数组的大小为n
在将其先前的计数求和成下一个索引之前,先获取计数数组
存储在其中的最大值的索引是给定数据的模式。
如果存在不止一个最大元素,那么我们可以选择其中一个
将值存储到另一个名为mode的单独变量中。
继续进行计数排序的常规处理。
在排序数组中,如果n为奇数,则中位数是排序数组的最中间元素;如果n为偶数,则取中间两个元素,然后求出它们的平均值即可得出中位数。
将值存储到另一个单独的变量中值。
#include <iostream>
using namespace std;
bool isRepresentedInDDigits(int num, int d, int base) {
if (d==1 && num < base)
return true;
if (d > 1 && num >= base)
return isRepresentedInDDigits(num/base, --d, base);
return false;
}
bool checkNumber(int num, int d) {
//一一检查所有基地
for (int base=2; base<=32; base++)
if (isRepresentedInDDigits(num, d, base))
return true;
return false;
}
int main() {
int num = 8;
int dig = 2;
if(checkNumber(num, dig))
cout << "Can be represented";
else
cout << "Can not be represented";
}输出结果
Can be represented