【问题标题】:How to find mode from an array如何从数组中查找模式
【发布时间】:2014-04-28 12:12:31
【问题描述】:

我一直在尝试让这个原型用于查找数组的模式,但它没有返回正确的东西,谁能告诉我我做错了什么。

  int mode(int array[], int size)
  {
      int x;
      int mode = 0;
      int largest = 0;

     for (x = 0; x < size; x++)
     {
         if (array[x] > largest)
         {
             largest = array[x];
             mode = x;
         }
      }
    return mode;
   }

【问题讨论】:

    标签: arrays mode


    【解决方案1】:

    首先如果那是 c++ 数组从 0 开始编号,所以 x 在 for 中应该是 0。 x 也应该检查

    【讨论】:

    • 抱歉,我忘了说它只是 C。不过我确实将 1 更改为 0。但我还应该检查 x
    • 如果是 c,0 开始规则仍然适用。是的,如果您保留
    • 嗯,我改了,结果还是不正确。
    • 我的意思是我在我的实际代码中改变了它,我只是忘了编辑那部分。
    【解决方案2】:

    在你提到的问题中,“prototype for find mode of an array”,但是这个程序是为了找到数组中最大数的位置,因为

    mode = x;      // x is the value of i which in-turn is the position of element in the array 
    

    并返回mode的值。所以显示了从第零个元素位置算起的最大元素的位置。

    如果你想让程序在数组中找到模式(最常出现的元素/数字),这里就是

    #include <stdio.h>
    
    int mode(int array[], int size);
    int main()
    {
        int Num[100],size,ret_Val,i;
        clrscr();
        printf("Enter the size of the array\n");
        scanf("%d",&size);
        printf("%d  ",size);
        for(i=0;i<size;i++)
        {
            scanf("%d",&Num[i]);
        }
        ret_Val=mode(Num,size);
        printf("Mode of the array is %d",ret_Val);
        getch();
        return 0;
    }
    
    int mode(int array[], int size)
    {
        int cntMde = 1;
        int i;
        int cnt = 1;
        int num = array[0];
        int mode = num;
    
        for ( i=1; i<size; i++)
        {
            if (array[i] == num) 
            {
                cnt++;
            }
            else
            {
                if (cnt > cntMde) 
                {
                    cntMde = cnt;
                    mode = num;
                }
                cnt = 1;
                num = array[i];
            }
        }
        return mode;
    }
    

    输出是

    Mode of the array is 44
    

    【讨论】:

    • 嗯,我认为它正在工作,但这只是巧合,虽然很接近
    • 这个答案有用吗? ,如果是请采纳答案
    • 但它对我有用,我正在编辑并给出完整的程序,尝试执行它。
    • 哦,它可能不起作用,因为在我的程序中,您输入了您希望输入的内容,以查找具有不同大小的数组的模式。
    • 你测试过这个程序吗?
    【解决方案3】:

    我分析了四种计算数组众数的方法:

    • 如果数组中的数字范围很小,则使用计数排序 - O(N) 时间,(N) 空间,但非常有效
    • 哈希表中数组中的索引元素 - O(N) 时间,O(N) 空间
    • 对数组进行排序,然后计算连续相等的元素 - O(NlogN) 时间,O(1) 空间
    • 对数组进行部分排序,但跳过小于当前候选者的分区 - O(NlogN) 时间,O(1) 空间,但比完全排序数组效率更高,因为将跳过许多分区

    您可以在本文中找到所有四种方法和性能比较的源代码:Finding Mode of an Array

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 2012-07-10
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多