/*
* MIN HEAP
* Date: 2013/4/5
* NolanJian
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#define MAXELEMENTS 32000
#define HEAP_FULL(n) (n == MAXELEMENTS - 1)
#define HEAP_EMPTY(n) (!n)
struct heapnode;
typedef struct heapnode Heap;
typedef Heap *Hp;
void InsertMinHeap(Heap item, int *n);
Heap DeleteMinHeap(int *n);
void Output(int *n);
void Input(int *n);
struct heapnode {
int key;
};
Heap heap[MAXELEMENTS];
int main() {
int n;
while(1) {
printf("Input n: ");
scanf("%d", &n);
Input(&n);
Output(&n);
}
}
void Output(int *n) {
int i;
Heap tmp;
while(!HEAP_EMPTY(*n)) {
tmp = DeleteMinHeap(n);
printf("%d ", tmp.key);
}
printf("\n************************************\n");
}
void Input(int *n) {
int tag[MAXELEMENTS], i = 0, k, m = *n;
Hp tmp;
srand((unsigned int)time(NULL));
memset(tag, 0, sizeof(tag));
while(i < m) {
while(1) {
k = rand() % MAXELEMENTS;
if(tag[k] == 0) {
tag[k] = 1;
break;
}
}
tmp = (Hp)malloc(sizeof(Heap));
tmp->key = k;
InsertMinHeap(*tmp, &i);
}
return ;
}
void InsertMinHeap(Heap item, int *n) {
int i;
if(HEAP_FULL(*n))
exit(1);
i = ++(*n);
while(i != 1 && item.key < heap[i / 2].key) {
heap[i] = heap[i / 2];
i /= 2;
}
heap[i] = item;
return ;
}
Heap DeleteMinHeap(int *n) {
int parent, child;
Heap item, temp;
item = heap[1];
temp = heap[(*n)--];
parent = 1;
child = 2;
while(child <= *n) {
if(child < *n && heap[child].key > heap[child + 1].key)
child++;
if(temp.key <= heap[child].key)
break;
heap[parent] = heap[child];
parent = child;
child *= 2;
}
heap[parent] = temp;
return item;
}
最小堆
最新推荐文章于 2022-10-27 20:35:10 发布