// BinaryHeapDelete.c
// 备注: 本程序显示结果应以二叉树形式而非数组形式排列
// FLAG = 0 最小堆
// FLAG = 1 最大堆
#define FLAG 0
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
typedef int DataType;
typedef unsigned char NumType; // 有效个数:2至255
// 堆元素数量上限
// ( 2 ^ ( sizeof ( NumType ) * 8 ) ) - 1
#define LIMIT ( NumType ) ( ( 1 << ( sizeof ( NumType ) << 3 ) ) - 1 )
typedef enum { false, true } bool ;
typedef struct
{
DataType data[LIMIT]; // 堆元素
NumType CurrentSize; // 当前堆元素数量
// 此处可添加堆的其它信息
} BinaryHeap;
bool BinaryHeapDelete(BinaryHeap * const);
int main(void)
{
BinaryHeap element;
NumType i;
srand((unsigned int)time(0));
element.CurrentSize = LIMIT;
for (i = 0; i < element.CurrentSize; ++i)
{
#if !FLAG // FLAG == 0
// rand() % 100 随机生成0至99共计100种随机数字
element.data[i] = rand() % 100;
if (i) // i非根
// 结点data[i]的父结点是data[(i - 1) / 2]
// 故儿子生成随机数再加上父亲的值 如此即可保证生成最小堆随机数
// element.data[i] = element.data[i] + element.data[(i - 1) / 2];
element.data[i] += element.data[(i - 1) >> 1];
#elif FLAG // FLAG == 1
if (i) // i != 0 i非根
// 结点data[i]的父结点是data[(i - 1) / 2]
// 故儿子生成随机数等于父亲的值减去随机值 如此即可保证生成最大堆随机数
// element.data[i] = element.data[(i - 1) / 2] - (rand() % 100);
element.data[i] = element.data[(i - 1) >> 1] - (rand() % 100);
else // i == 0 i为根
element.data[i] = 32767 - rand() % 100;
#endif
}
puts("生成随机数:\n");
for (i = 0; i < element.CurrentSize; ++i)
{
printf("%-5d\t", element.data[i]);
if (i % 10 == 9)
putchar('\n');
}
#if !FLAG // FLAG == 0
puts("\n\n最小堆删除元素后:\n");
#elif FLAG // FLAG == 1
puts("\n\n最大堆删除元素后:\n");
#endif
if (BinaryHeapDelete(&element))
for (i = 0; i < element.CurrentSize; ++i)
{
printf("%-5d\t", element.data[i]);
if (i % 10 == 9)
putchar('\n');
}
else
puts("堆元素数量为0!");
putchar('\n');
getch();
return 0;
}
/******************************以上代码仅供测试******************************/
// 最小/大堆删除元素
bool BinaryHeapDelete(BinaryHeap * const heap)
{
NumType hole, child;
DataType temp, DelElement = heap->data[0];
// if (heap->CurrentSize != 0)
if (heap->CurrentSize)
{
temp = heap->data[--heap->CurrentSize];
// for (hole = 0; 2 * hole < heap->CurrentSize; hole = child)
for (hole = 0; (hole << 1) < heap->CurrentSize; hole = child)
{
// child = 2 * hole + 1;
child = (hole << 1) + 1;
#if !FLAG // FLAG == 0
if (child + 1 < heap->CurrentSize && heap->data[child + 1] < heap->data[child])
#elif FLAG // FLAG == 1
if (child + 1 < heap->CurrentSize && heap->data[child + 1] > heap->data[child])
#endif
++child;
#if !FLAG // FLAG == 0
if (heap->data[child] < temp)
#elif FLAG // FLAG == 1
if (heap->data[child] > temp)
#endif
heap->data[hole] = heap->data[child];
else
break;
}
heap->data[hole] = temp;
return true;
}
else // heap->CurrentSize == 0
return false;
}
最小/大堆删除元素算法
最新推荐文章于 2024-03-19 17:49:56 发布