阅读背景:

算法导论(Problems 6-2) d-ary heap(多叉树实现堆)

来源:互联网 
#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{
	int d_dimential;
	int a_size;
	int h_size;
	int *arr;
}heap;

void Tune(heap& h,int start){
	int i = start;
	int index = i;
	int temp = h.arr[start];
	while (i*h.d_dimential+1 < h.h_size){
		int max_temp = temp;
		for (int j = i*h.d_dimential+1; j <= (i + 1)*h.d_dimential&&j<h.h_size; j++){
			if (max_temp < h.arr[j]){
				max_temp = h.arr[j];
				index =j;
			}
		}
		if (index == i) break;
		else{
			h.arr[i] = h.arr[index];
			i = index;
		}
	}
	h.arr[index] = temp;
}

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

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

int main(){
	heap h;
	cout << "Input the dimention of the heap:";
	cin >> h.d_dimential;
	cout << "Input the size of the data:";
	cin >> h.a_size;
	h.h_size = h.a_size;
	h.arr = new int[h.h_size];
	cout << "Input the data:";
	for (int i = 0; i <h.a_size; i++) cin >> h.arr[i];
	BuildHeap(h);
	cout << "The result of buiding:";
	for (int i = 0; i < h.a_size; i++) cout << h.arr[i]<<" ";
	cout << endl;
	HeapSort(h);
	cout << "The result of sorting:";
	for (int i = 0; i < h.a_size; i++) cout << h.arr[i] << " ";
	cout << endl;
	system("pause");
	return 0;
}#include<iostream>
#include<vector>
#include<st



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: