在C中找到数组中最大的十个数字

时间:2014-04-18 06:51:45

标签: c arrays algorithm max

我有一个int数组(数组的长度可以从11到500),我需要在另一个数组中提取最大的十个数字。

所以,我的起始代码可能就是这样:

arrayNumbers[n]; //array in input with numbers, 11<n<500

int arrayMax[10];

for (int i=0; i<n; i++){

    if(arrayNumbers[i] ....

    //here, i need the code to save current int in arrayMax correctly
}

//at the end of cycle, i want to have in arrayMax, the ten largest numbers (they haven't to be ordered)

在C中执行此操作的最有效方法是什么?

7 个答案:

答案 0 :(得分:3)

研究maxheap。保持大小为10的堆并忽略所有溢出元素。如果您遇到困难,请询问。

修改 如果元素数量少于20,则找到n-10个最小元素,如果数字是前10个数字,则休息。

Visualize a heap here

EDIT2:根据Sleepy的评论,我搜索并找到了this(我没有测试过)。您可以在(n)时间内找到第k个最大元素(在这种情况下为10)。现在在O(n)时间内,您可以找到大于或等于第k个最大数字的前10个元素。最终的复杂性是线性的。

答案 1 :(得分:1)

这是一个在线性时间内解决的算法:

  1. 使用selection algorithm,它可以在线性时间内有效地找到未排序数组中的第k个元素。您可以使用快速排序的变体或更强大的算法。

  2. 使用步骤1中的pivot获取前k个。

答案 2 :(得分:1)

这是我的想法:

  1. 将arrayNum的前10个元素插入arrMax。
  2. 对这10个元素进行排序arrMax [0] = min,arrMax [9] = max。
  3. 然后逐个检查剩余的元素,并将每个可能的候选人插入其正确的位置,如下(草稿):
  4. int k,r,p;

        for (int k = 10; k < n; k++)
       {
        r = 0;
        while(1)
        {
        if (arrMax[r] > arrNum[k]) break; // position to insert new comer
        else if (r == 10) break;  // don't exceed length of arrMax
        else r++;                 // iteration
        }
    
        if (r != 0)  // no need to insert number smaller than all members
        {
         for (p=0; p<r-1; p++) arrMax[p]=arrMax[p+1]; // shift arrMax to make space for new comer
         arrMax[r-1] = arrNum[k]; // insert new comer at it's position
        }
       } // done!
    

答案 3 :(得分:0)

对数组进行排序,并在另一个数组中插入Max 10元素

答案 4 :(得分:0)

你可以使用&#34;选择&#34;算法找到你的第i个最大数字(你可以把你喜欢的任何数字代替我)然后迭代数组并找到比i大的数字。在你的情况下,当然我= 10 ..

答案 5 :(得分:0)

以下示例可以为您提供帮助。它将原始数组中最大的10个元素排列成 arrMax ,假设你在原始数组中有所有正数 arrNum 。基于此,您还可以通过初始化 arrMax 的所有元素来处理负数,并使用可能的最小数字。

无论如何,使用10个元素的堆是一个更好的解决方案,而不是这个。

void main()
{
int arrNum[500]={1,2,3,21,34,4,5,6,7,87,8,9,10,11,12,13,14,15,16,17,18,19,20};
int arrMax[10]={0};

int i,cur,j,nn=23,pos;
clrscr();

for(cur=0;cur<nn;cur++)
{
    for(pos=9;pos>=0;pos--)
       if(arrMax[pos]<arrNum[cur])
         break;
    for(j=1;j<=pos;j++)
       arrMax[j-1]=arrMax[j];
    if(pos>=0)
       arrMax[pos]=arrNum[cur];
}

for(i=0;i<10;i++)
   printf("%d ",arrMax[i]);

getch();
}

答案 6 :(得分:0)

在提高算法效率时,从一个简单的实现开始并改进它通常是最好的(也是有益的)。因为在你的问题中,你显然甚至没有这个,效率可能是一个没有实际意义的点。

如果你从如何找到最大整数的简单问题开始:

  1. 将largest_found初始化为INT_MIN
  2. 使用:

    迭代数组

    IF值&gt; maximum_found THEN largest_found = value

  3. 要获得10个最大值,您执行相同的算法10次,但保留上一次迭代的last_largest及其索引,修改maximum_found测试:

    IF value > largest_found && 
       value <= last_largest_found &&
       index != last_largest_index 
    THEN
       largest_found = last_largest_found = value
       last_largest_index = index
    

    从那开始,然后问自己(或这里)关于效率。