算法导论(build the heap recursively 递归建堆)

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<xfunctional>
using namespace std;

typedef struct heap{
	int arr_size;
	int heap_size;
	int *arr;
}heap;

void Tune(heap& h,int start){
	int i = start;
	if (2 * i > h.heap_size) return;
	int index=-1;
	int max_temp = h.arr[i];
	if (h.arr[2 * i] > h.arr[i]){
		index = 2 * i;
		max_temp=h.arr[index];
	}
	if (2 * i + 1 <= h.heap_size){
		if (h.arr[2 * i + 1] > max_temp){
				max_temp = h.arr[2*i+1];
				index = 2 * i + 1;
			}
		}
	if (index == -1) return;
	else{
		swap(h.arr[index],h.arr[i]);
		Tune(h,index);
	}
}

void BuildHeap(heap &h){
	for (int i = h.heap_size / 2; i >0; i--){
		Tune(h,i);
	}
}

void heap_sort(heap &h){
	for (int i = h.heap_size; i > 1; i--){
		swap(h.arr[1], h.arr[h.heap_size]);
		h.heap_size--;
		Tune(h,1);
	}
}


int main(){
	heap h;
	cout << "Input the size of the array:";
	cin >> h.arr_size;
	h.arr = new int[h.arr_size+1];
	h.heap_size = h.arr_size;
	cout << "Input the element:";
	for (int i = 1; i <= h.arr_size; i++) cin >> h.arr[i];
	BuildHeap(h);
	cout << "After build:";
	for (int i = 1; i <= h.arr_size; i++) cout << h.arr[i] << " ";
	cout << endl;
	heap_sort(h);
	cout << "After sort:";
	for (int i = 1; i <= h.arr_size; i++) cout << h.arr[i]<<" ";
	cout << endl;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值