标签:change 最大的 实现 ret out using ++ name ios
根据算法导论里的伪代码实现
#include <iostream> using namespace std; void exchange(int a[], int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } void adjustTree(int a[], int i, int total) { int l = i * 2; int r = i * 2 + 1; //取左右孩子中最大的 int maxIndex = -1; if(l <= total && a[l] > a[i]) { maxIndex = l; } else maxIndex = i; if(r <= total && a[r] > a[maxIndex]) { maxIndex = r; } if(maxIndex != i) { exchange(a, i, maxIndex); //TODO 优化 adjustTree(a, maxIndex, total); } } void buildTree(int a[], int total) { for(int i = total / 2; i >= 1; i--) { adjustTree(a, i, total); } } /** * 大堆 */ int main() { int a[] = { 0, 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 }; int total = 10; buildTree(a, total); for(int i = 1; i <= total; i++) cout << " " << a[i]; cout << endl; int t2 = total; for(int i = total; i >= 2; i--) { exchange(a, 1, t2); t2--; adjustTree(a, 1, t2); } for(int i = 1; i <= total; i++) cout << " " << a[i]; cout << endl; return 0; }
标签:change 最大的 实现 ret out using ++ name ios
原文地址:http://www.cnblogs.com/shuiyonglewodezzzzz/p/6886608.html