我正在寻找一种确定C ptr数组中哪个元素出现次数最多(模式)的优雅方法.
例如,在
{"pear", "apple", "orange", "apple"}
“苹果”元素是最常见的元素.
我以前的尝试失败了
编辑:数组已被排序.
int getMode(int *students,int size)
{
int mode;
int count=0,
maxCount=0,
preVal;
preVal=students[0]; //preVall holds current mode number being compared
count=1;
for(int i =0; i
{
if(students[i]==preVal) //checks if current mode is seen again
{
count++; //The amount of times current mode number has been seen.
if(maxCount
{
maxCount=count; //the larger it mode that has been seen is now the maxCount
mode=students[i]; //The current array item will become the mode
}else{
preVal = students[i];
count = 1;
}
}
}
return mode;
}