二叉堆 删除 插入 调整 堆排序

以最大堆为例

#include<iostream>
#define MAX 10000
using namespace std;
typedef struct Heap Heap;
struct Heap{
	int size;
	int data[MAX];
};
//堆调整 
void adjust_heap(Heap *heap, int size, int i){
	int parent, child;
	int t = heap->data[i];
	
	for(parent = i; 2*parent+1 < size; parent = child){
		child = parent*2+1;
		if(child + 1 < size && heap->data[child] < heap->data[child+1])
			++child;
		if(t < heap->data[child])
			heap->data[parent] = heap->data[child];
		else
			break;		
	}
	heap->data[parent] = t;
} 
//建立堆(调整法) 
Heap create_heap(int size){
	Heap heap;
	heap.size = size;
	int x;
	for(int i = 0; i < size; ++i){
		scanf("%d",&x);
		heap.data[i] = x;
	}
	for(int i = heap.size/2-1; i >=0 ; --i){
			adjust_heap(&heap, heap.size, i);
		}
	return heap;
}

void swap(int *a, int *b){
	int t = *a; *a = *b; *b = t;
} 
//堆排序 
void heap_sort(Heap *heap){
		for(int i = heap->size-1; i > 0 ; --i){
			swap(heap->data[0], heap->data[i]);
			adjust_heap(heap,i,0);
		}	
} 
//删除 任意元素 
void heap_delet_val(Heap *heap, int val){
	int i;
	for(i = 0; i < heap->size; ++i){
		if(heap->data[i] == val)
			break;
	} 
	swap(&heap->data[i], &heap->data[heap->size-1]);
	--heap->size;
	adjust_heap(heap, heap->size, i);
}
//删除顶部元素 
int heap_delet_max(Heap *heap){
	int val = heap->data[0];
	swap(heap->data[0], heap->data[heap->size-1]);
	--(heap->size);
	adjust_heap(heap, heap->size, 0);
	return val;
}
//堆插入 
void heap_insert(Heap *heap, int val){
	++heap->size;
	heap->data[heap->size-1] = val;
	int i; 
	// 判断条件 写成 i!=0 而不能写成(i-1)/2 >= 0 后者 会进入死循环  
	for(i = heap->size-1; i != 0 && heap->data[(i-1)/2] < val; i = (i-1)/2){
		heap->data[i] = heap->data[(i-1)/2];
	}
	heap->data[i] = val;	
}

int main()
	{
		int n;
		scanf("%d",&n);
		Heap heap = create_heap(n);
		//heap_sort(&heap);
		int old_size = heap.size;//删除元素 输出的时候 heap->size会变化 要提前记录size 
		for(int i = 0; i < heap.size; ++i){
			//printf("size = %d",heap.size);
			printf("%d ",heap.data[i]);
		}
		printf("\n");
		heap_insert(&heap, 5);
		for(int i = 0; i < heap.size; ++i){
			printf("%d ",heap.data[i]);
		}
		return 0;
	}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值