最大堆的插入與刪除操做

#include<stdio.h>code

#include<stdlib.h>ci

#define elementType intelement

//定義堆的結構體get

typedef struct structHeap {it

elementType *data;

int size;

int capacity;

}*MaxHeap;io

//初始化堆循環

MaxHeap init(int MaxSize) {di

MaxHeap h =(MaxHeap)malloc(sizeof(struct structHeap));

h->data = (elementType *)malloc((MaxSize+1)*sizeof(elementType));

h->size = 0;

h->capacity = MaxSize;

h->data[0] = 11111111;

return h;

}co

// 判斷是否爲空let

bool isFull(MaxHeap h) {

return h->size == h->capacity;

}

void insert(MaxHeap h, elementType x) {

if (isFull(h)) {

	printf("堆已經滿了\n");
	
	return;
}

int i;

i = h->size;

i++;

h->size++;

printf("%d\n", i);

for (; h->data[i / 2] < x; i = i / 2)

	h->data[i]=h->data[i/2]; 
	
h->data[i] = x;

}

//刪除的過程與插入的過程相反

void delete_max(MaxHeap h) {

if (h->size == 0) {

	printf("堆已經空了\n");
	
	return;
}

int  max = h->data[1];

int parent;

int child;

int temp = h->data[h->size];

h->size--;

for (parent = 1; parent * 2 <= h->size; parent = child) {

	child = parent * 2;
	
	//判斷左孩子與右孩子誰大
	
	if (child != h->size && (h->data[child] < h->data[child + 1]))
	
		child++;
		
	 //若是找到temp大於某個節點,跳出循環
	 
	if (temp >= h->data[child])break;
	
	else //交換下位置,由於temp不適合插入這個位置
	
		h->data[parent] = h->data[child];
}

//最後把找到的位置將temp插入

h->data[parent] = temp;

printf("刪除成功\n");

}

int main() {

MaxHeap head = init(20);
bool b = isFull(head);
int a[] = { 2,3,1,7,6,9,4,5 };
int length = sizeof(a) / sizeof(a[0]);
for(int i=0;i<length;i++)
insert(head,a[i]);
delete_max(head);
for (int i = 0; i < length-1; i++)
	printf("%d\n", head->data[i + 1]);
getchar();
return 0;

}

相關文章
相關標籤/搜索