C ++计算排序后的数组的方式 [英] C++ Calculating the Mode of a Sorted Array

查看:158
本文介绍了C ++计算排序后的数组的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写一个C ++ code,它找到了一个数组的中位数和模式。我听说它更容易找到一个阵列模式后的数字已经进行了分类。我排序的功能,但仍然无法找到的模式。

  INT计数器= 0;
    对于(INT通= 0;通过<大小 - 1;传++)
        对于(诠释计数=传+ 1; COUNT<大小;计数++){
            如果(阵列[统计] ==阵列[通])
                反++;
            COUT<< 模式是:&所述;&下;计数器<< ENDL;


解决方案

如果数组已被排序,你可以一次算一个数的发生。然后,只需保存具有最大的出现次数。而且你可以找出只有一个循环模式。
否则,你就必须做一比for循环。
请参见下面的链接细节的例子
查找,该模式的一-SET-的 - 数字

下面是code,

  INT数=阵列[0];
INT模式=号;
诠释计数= 1;
INT countMode = 1;的for(int i = 1; I<大小;我++)
{
      如果(阵列[我] ==号)
      {//计算当前数的出现
         countMode ++;
      }
      其他
      {//现在这是一个不同的数字
            如果(计数> countMode)
            {
                  countMode =计数; //模式是最大ocurrences
                  模式=号;
            }
           数= 1; //重新设置计数的新号码
           数=阵列[我]
  }
}COUT<< 模式:<<模式<< ENDL;

I have to write a C++ code that finds the median and mode of an array. I'm told that it's much easier to find the mode of an array AFTER the numbers have been sorted. I sorted the function but still cannot find the mode.

 int counter = 0;
    for (int pass = 0; pass < size - 1; pass++)
        for (int count = pass + 1; count < size; count++) {
            if (array [count] == array [pass])
                counter++;
            cout << "The mode is: " << counter << endl; 

解决方案

If the array has been sorted already, you can count the occurrences of a number at once. Then just save the number that has biggest occurrences. And you can find out the mode in only one for-loop. Otherwise, you'll have to do more than one for-loops. See a details example at the link below Find-the-Mode-of-a-Set-of-Numbers

Here is the code,

int number = array[0];
int mode = number;
int count = 1;
int countMode = 1;

for (int i=1; i<size; i++)
{
      if (array[i] == number) 
      { // count occurrences of the current number
         countMode++;
      }
      else
      { // now this is a different number
            if (count > countMode) 
            {
                  countMode = count; // mode is the biggest ocurrences
                  mode = number;
            }
           count = 1; // reset count for the new number
           number = array[i];
  }
}

cout << "mode : " << mode << endl;

这篇关于C ++计算排序后的数组的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆