最小/大堆添加元素算法

来源:互联网 发布:淘宝登录限制怎么办 编辑:程序博客网 时间:2024/04/29 04:59

// BinaryHeapAdd.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 BinaryHeapAdd(BinaryHeap * const, const DataType);int main(void){BinaryHeap element;DataType NewElement;NumType i;srand((unsigned int)time(0));element.CurrentSize = LIMIT - 1;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 == 1if (i) // i != 0i非根// 结点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 == 0i为根element.data[i] = 32767 - rand() % 100;#endif}#if !FLAG // FLAG == 0NewElement = rand() % 1000;#elif FLAG // FLAG == 1NewElement = 32767 - rand() % 1000;#endifprintf("新元素: %d\n\n", NewElement);puts("生成随机数:\n");for (i = 0; i < element.CurrentSize; ++i){printf("%-5d\t", element.data[i]);if (i % 10 == 9)putchar('\n');}#if !FLAG // FLAG == 0puts("\n\n最小堆添加元素后:\n");#elif FLAG // FLAG == 1puts("\n\n最大堆添加元素后:\n");#endifif (BinaryHeapAdd(&element, NewElement))for (i = 0; i < element.CurrentSize; ++i){printf("%-5d\t", element.data[i]);if (i % 10 == 9)putchar('\n');}elseputs("堆元素数量超上限!");putchar('\n');getch();return 0;}/******************************以上代码仅供测试******************************/// 最小/大堆添加元素bool BinaryHeapAdd(BinaryHeap * const heap, const DataType NewElement){NumType hole = heap->CurrentSize, index;if (heap->CurrentSize < LIMIT){#if !FLAG // FLAG == 0// for (; hole > 0 && NewElement < heap->data[index = (hole - 1) / 2]; hole = index)for (; hole && NewElement < heap->data[index = ((hole - 1) >> 1)]; hole = index)#elif FLAG // FLAG == 1// for (; hole > 0 && NewElement > heap->data[index = (hole - 1) / 2]; hole = index)for (; hole && NewElement > heap->data[index = ((hole - 1) >> 1)]; hole = index)#endifheap->data[hole] = heap->data[index];heap->data[hole] = NewElement;++heap->CurrentSize;return true;}else // heap->CurrentSize >= MAXHEAPreturn false;}

0 0