网上关于小根堆(堆排序)的博客不是很多,有些代码还不全,这里找到一个适合初学者的代码分享给大家。 建议看下面代码前先把堆排序的图示方法看一遍,结合代码和书本示例看的话很容易懂 原作者在他的博客里已经写的很详细了,因为VS对代码的要求比较高,我对原作者分配空间和增加空间的函数用了更规范的写法,下面是代码:
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
struct HeapSq
{
ElemType* heap;
int len;
int MaxSize;
};
void InitHeap(struct HeapSq* HBT, int MS)
{
if (MS <= 0 )
{
printf ("数组长度参数不合适,需重新给定!\n" );
exit (1 );
}
HBT->heap = malloc (MS*sizeof (ElemType));
if (!HBT->heap)
{
printf ("用于动态分配的内存空间用完,退出运行!\n" );
exit (1 );
}
HBT->MaxSize = MS;
HBT->len = 0 ;
}
void ClearHeap(struct HeapSq* HBT)
{
if (HBT->heap != NULL)
{
free (HBT->heap);
HBT->len = 0 ;
HBT->MaxSize = 0 ;
}
}
int EmptyHeap(struct HeapSq* HBT)
{
if (HBT->len == 0 )
return 1 ;
else
return 0 ;
}
void InsertHeap(struct HeapSq* HBT, ElemType x)
{
int i;
if (HBT->len == HBT->MaxSize)
{
ElemType *p;
p = realloc(HBT->heap, 2 *HBT->MaxSize*sizeof (ElemType));
if (!p)
{
printf ("存储空间用完!\n" );
exit (1 );
}
printf ("存储空间已扩展为原来的2倍!\n" );
HBT->heap = p;
HBT->MaxSize = 2 *HBT->MaxSize;
}
HBT->heap[HBT->len] = x;
HBT->len++;
i = HBT->len - 1 ;
while (i != 0 )
{
int j = (i - 1 ) / 2 ;
if (x >= HBT->heap[j])
break ;
HBT->heap[i] = HBT->heap[j];
i = j;
}
HBT->heap[i] = x;
}
ElemType DeleteHeap(struct HeapSq* HBT)
{
ElemType temp, x;
int i, j;
if (HBT->len == 0 )
{
printf ("堆已空,退出运行!\n" );
exit (1 );
}
temp = HBT->heap[0 ];
HBT->len--;
if (HBT->len == 0 )
return temp;
x = HBT->heap[HBT->len];
i = 0 ;
j = 2 * i + 1 ;
while (j <= HBT->len - 1 )
{
if (j < HBT->len - 1 && HBT->heap[j] > HBT->heap[j+1 ])
j++;
if (x <= HBT->heap[j])
break ;
HBT->heap[i] = HBT->heap[j];
i = j;
j = 2 * i + 1 ;
}
HBT->heap[i] = x;
return temp;
}
void main()
{
int i, x;
int a[8 ] = {23 ,56 ,40 ,62 ,38 ,55 ,10 ,16 };
struct HeapSq b;
InitHeap(&b, 10 );
for (i = 0 ; i < 8 ; i++)
InsertHeap(&b, a[i]);
while (!EmptyHeap(&b))
{
x = DeleteHeap(&b);
printf ("%d" , x);
if (!EmptyHeap(&b))
printf ("," );
}
printf ("\n" );
system("pause" );
ClearHeap(&b);
}
原作者对堆排序的理解很透彻,代码写的也比较规范,对空间的申请和释放都很正确,推荐大家直接看他的博客(见参考部分)
参考: https://www.cnblogs.com/zl0372/p/min_heap.html