查找最小的K个元素,使用最大堆。

查找最小的K个元素,使用最大堆,具体代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
void swap(int *a, int *b)
{     int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
void heap_adjust(int *a, int i, int size)
{
    int lchild = 2 * i;
    int rchild = 2 * i + 1;
    int max = i;
    if (i <= size / 2) //大于size/2的为叶子节点,不需要调整
    {         if (lchild <= size && a[lchild]>a[max])
            max = lchild;
        if (rchild <= size && a[rchild]>a[max])             max = rchild;
        if (max != i)
        {
            swap(&a[i], &a[max]);
            heap_adjust(a, max, size); //依此调整下面的子树,为了防止交换之后不满足堆的性质
        }
    }
} void create_heap(int *a, int size)
{
    int i = 0;
    for (i = size / 2; i >= 1; i--)
        heap_adjust(a, i, size);
} void heap_sort(int *a, int size)
{
    int i = 0;
    int temp = 0;
    create_heap(a, size);
    for (i = size; i >= 1; i--)
    {         swap(&a[i], &a[1]);
        heap_adjust(a, 1, i - 1);
    }
} int main(int argc, char **argv)
{
    int a[100];
    int size = 0;
    int nTemp = 0;
    cout << "堆个数:";
    while (scanf("%d", &size) == 1 && size >0)
    {
        int i = 0;
        for (i = 1; i <= size; i++)
            scanf("%d", &a[i]);
        heap_sort(a, size);
        printf("请输入要显示的K\n");
        scanf("%d", &nTemp);
        for (i = 1; i <= nTemp; i++)
            printf("%d ", a[i]);
    }
    return 0;
}

运行效果如图1所示:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAqUAAAELCAIAAABvRGhmAAAQIUlEQVR4nO3d748c50EH8P1z7g/Ie7+0MAIOpQYiVPnAqtRDCAlZVAKBLECoaU1a2rrCDoSQlKaRCQlnN4rTNM6dK+jRJFLP1CXGAnpFaitydz7bobbpi+PF2uvZmWeendkf8+w+9/noq+pub3bm2XF63/l9vcvnl0VERCTv9C6fX97fXBUREZGx8+3l5XlI3fD0vYiIyBSSvOn1vYiIyMyTvOn1vYiIyMyTvOn1vYiIyMyTvOn1vYiIyM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fR9H6/M6uut+r6uIyNaVeYY8x85ZXxtBJfbfFMDgMNpLvq+NKZgbxWrrlr/k/R9cIOjSek2/HqSKesmrvZ98QsAKJmLvo+Ua2myXqXzIn0/skpHvmXkZsTkfd/22+Dc9D0AcXPR96Ux1W0NlH469b5vWPbVpQcH1mrOzbcGgtMXF63yAahK2ffFvdKS4hBLzVqarK7v62ov8npwq6JOXd83GUm8wlv1fXXY+h6AqmR933xvuPRi8I1NOnLkj4pja9iakTGM/WJ86ycyBwCoM1/H8+t2kXv1fV+3nx0R3xqo23UuvdhE3aLjI4xsuzR5OwBUpX++XqTegq8POq+6BRB5e3VupXfVNXTzeTY04dyUPQBjSN/3AMCs6XsAyJ++B4D86XsAyF+yv48Xv0QOAJiiNH2f+lMDwOGi7wEgf/oeAPKX+Px96o8PAIdCyuvzVT4AdEPfA0D+Up6/1/cA0I0E+/fO3wNAxzxfDwDyp+8BIH/6HgDyp+8BIH/6HgDyp+8BIH/6HgDyl/j+++a34LeastXMx34egEcIALAoEv99vIaV2ba8m79r7Of9eWQQAAuk1PcrKyuldq++MuXn6cYrc7yd9erXbd/bZEp9D8CiqPZ9seBL306z71tV5njNOqO+L32EtqMCgO4F+77f8cWvZ9L3vRkczx/vLeNteeh7ABZF9fz9yrCZnL9vu4s8uyPzbd+1HtJ2QQDQseD1epGyn1rf9xc/i74fu4O72aoAgO7VXZ9fV/ZTO57fN/W+b7sxMcnxeX0PwKKY9/vv2x48H+Nge6uJJ3wXACTh+XoAkD99DwD50/cAkL+u+15EREQWJWP2vYiIiGQQfS8iIpJ/9L2IiEj+0fciIiL5R9+LiIjkH30vIiKSf/S9iIhI/tH3IiIi+edh34uIiEje+X9b1rCu1CUFKQAAAABJRU5ErkJggg==" alt="" />

图1 运行效果

上一篇:Unity3d webplayer获取url参数


下一篇:【编程题目】查找最小的 k 个元素