数组中最低的n个数字

时间:2016-12-09 06:04:02

标签: c arrays algorithm

如何在数组中组合一组最低或最大的数字?例如,如果我想在大小为1000的数组中找到最低的10个数字。

我在C工作,但我不需要语言特定的答案。我只是试图想办法处理这类任务,因为它最近出现了很多。

4 个答案:

答案 0 :(得分:5)

QuickSelect算法允许分离预定义数量的最低和最大数字(没有完全排序)。它使用像Quicksort算法这样的分区程序,但在枢轴找到所需位置时停止。

答案 1 :(得分:1)

方法1:对数组进行排序

您可以对数组执行类似快速排序的操作并获取前10个元素。但这是相当低效的,因为你只对前10个元素感兴趣,并为此排序整个数组是一种过度杀伤。

方法2:进行线性遍历并跟踪10个元素。

int lowerTen = malloc(size_of_array);

//'array' is your array with 1000 elements
for(int i=0; i<size_of_array; i++){
    if(comesUnderLowerTen(array[i], lowerTeb)){
        addTolowerTen(array[i], lowerTen)
    }
}

int comesUnderLowerTen(int num, int *lowerTen){
    //if there are not yet 10 elements in lowerTen, insert.

    //else if 'num' is less than the largest element in lowerTen, insert.
}

void addToLowerTen(int num, int *lowerTen){
    //should make sure that num is inserted at the right place in the array
    //i.e, after inserting 'num' *lowerTen should remain sorted
}

毋庸置疑,这不是一个有效的例子。也只有在'lowerTen'数组需要维护少量元素的排序列表时才这样做。如果您需要1000个元素数组中的前500个元素,这将不是首选方法。

方法3:填充原始数组时执行方法2

仅当您的原始1000个元素数组逐个填充时才有效 - 在这种情况下,不是在1000个元素数组上进行线性遍历,而是可以在填充原始数组时维护“lowerTen”数组。

方法4:不要使用数组

如果您可以根据原始数组维护二进制搜索树之类的数据结构,那么这样的任务会更容易。但是,再次,在您的阵列上构建BST然后找到前10个元素将与对数组进行排序然后执行相同操作一样好。只有在您的用例需要搜索非常大的数组并且数据需要在内存中时才能执行此操作。

答案 2 :(得分:0)

实施优先级队列。 遍历所有数字并将它们添加到该队列。 如果该队列的长度等于10,则开始检查当前数字是否低于该队列中的最高数字。 如果是,请删除该最高编号并添加当前编号。

毕竟,您将拥有一个优先级队列,其中包含数组中最低的10个数字。 (所需时间应为O(n),其中n是数组的长度)。

如果您需要更多提示,请添加评论:)

答案 3 :(得分:0)

以下代码

  1. 干净地编译
  2. 执行所需的功能
  3. 可能不是最有效的
  4. 处理重复项
  5. 将需要修改以处理小于0的数字
  6. 现在是代码

    #include <stdlib.h>  // size_t
    
    void selectLowest( int *sourceArray, size_t numItemsInSource, int *lowestDest, size_t numItemsInDest )
    {
        size_t maxIndex = 0;
        int    maxValue = 0;
    
        // initially populate lowestDest array
        for( size_t i=0; i<numItemsInDest; i++ )
        {
            lowestDest[i] = sourceArray[i];
            if( maxValue < sourceArray[i] )
            {
                maxValue = sourceArray[i];
                maxIndex = i;
            }
        }
    
        // search rest of sourceArray and 
        // if lower than max in lowestDest, 
        // then 
        //    replace
        //    find new max value 
        for( size_t i=numItemsInDest; i<numItemsInSource; i++ )
        {
            if( maxValue > sourceArray[i] )
            {
                lowestDest[maxIndex] = sourceArray[i];
    
                maxIndex = 0;
                maxValue = 0;
                for( size_t j=0; j<numItemsInDest; j++ )
                {
                    if( maxValue < lowestDest[j] )
                    {
                        maxValue = lowestDest[j];
                        maxIndex = j;
                    }
                }
            }
        }
    } // end function: selectLowest
    
相关问题