sir*_*isp 3 c++ arrays sorting algorithm
我需要编写一个函数来查找数组的模式.我不擅长提出算法,但我希望其他人知道如何做到这一点.
我知道数组的大小和每个元素中的值,并且我将数组从最小到最大排序.
数组将传递给模式函数
mode = findMode(arrayPointer,sizePointer);
更新:
看完评论后我试过这个
int findMode(int *arrPTR, const int *sizePTR)
{
int most_found_element = arrPTR[0];
int most_found_element_count = 0;
int current_element = arrPTR[0];
int current_element_count = 0;
int count;
for (count = 0; count < *sizePTR; count++)
{
if(count == arrPTR[count])
current_element_count++;
else if(current_element_count > most_found_element)
{
most_found_element = current_element;
most_found_element_count = current_element_count;
}
current_element = count;
current_element_count=1;
}
return most_found_element;
}
Run Code Online (Sandbox Code Playgroud)
如果有人能把我排除在外,我仍然难以掌握这个算法.我从来没有使用过矢量,所以不要真正理解其他的例子.
你几乎拥有一切.
您可以利用数组排序的事实.
只需通过数组跟踪当前相等的连续数字,以及在该点之前找到的最大数量的相等连续数字(以及产生它的数字).最后,您将获得最多的相等连续数字,并产生哪个数字.这将是模式.
注:对于那些不解决不进行排序要求阵列,见例如一个基于直方图的方式在一个相关的问题.
set most_found_element to the first element in the array
set most_found_element_count to zero
set current_element to the first element of the array
set current_element_count to zero
for each element e in the array
if e is the same as the current_element
increase current_element_count by one
else
if current_element_count is greater than most_found_element_count
set most_found_element to the current_element
set most_found_element_count to current_element_count
set current_element to e
set current_element_count to one
if current_element_count is greater than most_found_element_count
set most_found_element to the current_element
set most_found_element_count to current_element_count
print most_found_element and most_found_element_count
Run Code Online (Sandbox Code Playgroud)
我以为名字会解释这一点,但是我们开始:
When we start, no element has been found the most times
so the "high-score" count is zero.
Also, the "current" value is the first, but we haven't looked at it yet
so we've seen it zero times so far
Then we go through each element one by one
if it's the same as "current" value,
then add this to the number of times we've seen the current value.
if we've reached the next value, we've counted all of the "current" value.
if there was more of the current value than the "high-score"
then the "high-score" is now the current value
and since we reached a new value
the new current value is the value we just reached
Now that we've seen all of the elements, we have to check the last one
if there was more of the current value than the "high-score"
then the "high-score" is now the current value
Now the "high-score" holds the one that was in the array the most times!
Run Code Online (Sandbox Code Playgroud)
还要注意:我的原始算法/代码有一个错误,循环结束后我们必须对“当前”进行额外的检查,因为它永远找不到“最后一个之后”。