cpp
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
Heapsort(nums);
return nums;
}
void Heapsort(vector<int>& nums)
{
int n = nums.size();
for(int i = (n/2) - 1; i>=0; i--)
{
Adjustdown(nums, i, n);
}
for(int i = n-1; i>=0; i--)
{
swap(nums[0], nums[i]);
Adjustdown(nums, 0, i);
}
}
void Adjustdown(vector<int>& nums, int root, int n)
{
int lson = 2 * root + 1;
while(lson < n)
{
if((lson + 1) < n && nums[lson] < nums[lson + 1])
{
lson = lson + 1;
}
if(nums[lson] > nums[root])
{
swap(nums[lson], nums[root]);
root = lson;
lson = 2 * root + 1;
}
else
break;
}
}
void swap(int& a, int& b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
};
堆排序
分两步:
1 大顶堆
2 有序的剩余元素、自上而下