八大排序之堆排序C++详解/C++堆排序/堆排 题目链接思路分析代码实现 题目链接 912. 排序数组 思路分析 代码实现 class Solution { public: void Swap(int& a, int& b) { int tmp = a; a = b; b = tmp; } void adjustDown(vector<int>& nums, int root, int n) { int parent = root; int child = parent*2 + 1; //这里建立的是一个大顶堆,因此要找子结点中较大的一个 while(child < n) { if( (child+1) < n && nums[child] < nums[child+1]) child++; if(nums[parent] < nums[child]) { Swap(nums[parent], nums[child]); parent = child; child = parent*2 + 1; } else break; } } vector<int> sortArray(vector<int>& nums) { //先建堆 从最后一个节点的父节点开始 int n = nums.size(); for(int i = ((n-1)-1)/2; i >= 0; --i) { adjustDown(nums, i, n); } int end = n-1; while(end > 0) { Swap(nums[0], nums[end]); adjustDown(nums, 0, end); --end; } return nums; } };