复杂度和稳定性
时间复杂度:最好、最坏、平均:O(N*ln(N))
稳定性:不稳定
CPP实现:
#include <vector>
#include <time.h>
#include <stdlib.h>
using namespace std;
void make_heap_max(vector<int>& v, int start, int end)
{
int dad = start;
int son = dad * 2 + 1;
while(son <= end)
{
if(son + 1 <= end && v[son] < v[son + 1])
son++;
if(v[dad] > v[son])
return;
else
{
swap(v[dad], v[son]);
dad = son;
son = dad * 2 + 1;
}
}
}
void heap_sort(vector<int>& v)
{
size_t size = v.size();
for(int i = size / 2 - 1; i >= 0; --i)
make_heap_max(v, i, size - 1);
for(int i = size - 1; i > 0; --i)
{
swap(v[0], v[i]);
make_heap_max(v, 0, i - 1);
}
}
int main(int argc, char* argv[])
{
srand(time(NULL));
vector<int> nums;
int size = rand() % 100 + 10;
for(int i = 0; i < size; ++i)
{
nums.push_back(rand() % 100);
}
heap_sort(nums);
return 0;
}