标签:
#include<iostream> #include<algorithm> using namespace std; long save[50010]; long savei = 1; inline void sawp(long &a, long &b) { long temp = a; a = b; b = temp; } bool judgeIFfix(long arr[], long node, long n) { if (2 * node > n) return false;//没有子节点,返回false if (arr[node] < arr[2 * node]) return true;//左节点比它大,返回true if (2 * node + 1 <= n)//存在右节点 { if (arr[node] < arr[2 * node + 1]) return true;//右节点比它大,返回true } return false;//不存在子节点比它大,返回false } void max_heapify(long arr[],long node, long n) { if (2 * node > n) return;//判断node是否有子节点,没有就返回 long largest; if (arr[node] < arr[2 * node]) largest = 2 * node; else largest = node; if (2 * node + 1 <= n)//右节点都没有超出范围n,左节点已在上边处理 { if (arr[largest] < arr[2 * node + 1]) largest = 2 * node + 1; } if (largest != node) swap(arr[node], arr[largest]); if (judgeIFfix(arr,2*node,n)) max_heapify(arr, 2 * node, n);//判断node的左节点是否需要fix、 if (judgeIFfix(arr,2*node+1,n)) max_heapify(arr, 2 * node + 1, n);//判断node的右节点是否需要fix } void heapsort(long arr[], long n) { long lastfather = (n + 1) / 2; for (long i = lastfather; i >= 1; i--)//生成最大堆 max_heapify(arr, i, n); for (long i = n; i >=1; i--) { save[savei++] = arr[1];//每次从堆中选取最大元素 swap(arr[i], arr[1]);//将最大元素与最后一个元素交换 max_heapify(arr, 1, i-1); } } int main() { long n, arr[50010]; cin >> n; for (long i = 1; i <= n; i++) cin >> arr[i]; heapsort(arr, n); for (long i = savei - 1; i >= 1; i--) cout << save[i] << endl; system("pause"); return 0; }
标签:
原文地址:http://www.cnblogs.com/anilop/p/5562506.html