借助大顶堆实现筛选前N个最小值

#include <stdio.h>
#include <memory.h>
#include <assert.h>

//heap[0]不用,数据从下标1开始存放,(targetPos,endPos]的数据已初始化为大顶堆
void HeapAdjust(int* heap, int targetPos, int endPos)
{
    assert(heap);
    int temp = heap[targetPos];
    int i;
    for (i = targetPos*2;  i <= endPos; i <<= 1)
    {
        if (i < endPos && heap[i+1] > heap[i])
        {
            ++i;
        }
        if (heap[i] <= temp)
        {
            break;
        }

        heap[targetPos] = heap[i];
        targetPos = i;
    }
    heap[targetPos] = temp;
}

//p[0]用于存放数组的长度(不包括下标为0的元素)
void GetPartSmallestValue(const int* array, int* partSmallestValue)
{
    assert(array && partSmallestValue);
    int* heap = partSmallestValue;
    int arrayLen = array[0];
    int heapLen = heap[0];

    //取前M个元素
    memcpy(heap+1,array+1,heapLen*sizeof(int));

    //建立大顶堆
    int i;
    for (i = heapLen/2; i > 0; --i)
    {
        HeapAdjust(heap,i,heapLen);
    }

    //依次遍历无序数组,小于堆顶元素,替换,从新调整大顶堆
    for (i = heapLen + 1; i <= arrayLen; ++i)
    {
        if (array[i] < heap[1])
        {
            heap[1] = array[i];
            HeapAdjust(heap,1,heapLen);
        }
    }
}


void main()
{
    int array[] = {10,0,3,4,5,2,32,3,8,5,34};
    int part[5] ={4};
    GetPartSmallestValue(array,part);
    int i;
    for (i = 1; i < 5; ++i)
    {
        printf("%d ",part[i]);
    }
    printf("\n");
}


你可能感兴趣的:(借助大顶堆实现筛选前N个最小值)