查找最小的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所示:图1 运行效果