void heapify(int tree[], int n, int i)//构建堆排序规则 这里构建的是最大堆
{
if (i >= n)return;
int max = i;
int c1 = 2 * i + 1;
int c2 = 2 * i + 2;
if (c1<n && tree[c1]>tree[max])
{
max = c1;
}
if (c2<n && tree[c2]>tree[max])
{
max = c2;
}
if (max != i)
{
swap(tree[max], tree[i]);
heapify(tree, n, max);
}
}
void bulid_heap(int tree[], int n)//建堆过程
{
int last_node = n - 1;//数组最后一个元素
int parent = (last_node - 1) / 2;//由关系式可以推出这个元素的父节点下标;
int i;
for (i = parent;i >= 0;i--)
{
heapify(tree, n, i);//对所有父节点进行heapify;
}
}
void heap_sort(int tree[], int n)//排序
{
bulid_heap(tree, n);//建堆
int i;
for (i = n - 1;i >= 0;i--)
{
swap(tree[i], tree[0]);//把最后一个节点和当前建好堆的最大元素交换,类似冒泡把最大值弄到数组最后;
heapify(tree, i, 0);//然后此时数组下标也跟着降序,下次最大值就会排在上一次的前面。
}
}
//一个完成的heap_sort分三步;
//1.建立排序规则,2根据规则建立堆,3将元素交换放到数组后面(间接排序);
void main()
{
int tree[6] = { 2,5,3,1,10,4 };
int n = 6;
heap_sort(tree, n);
for (auto i : tree)
{
cout << i;
}
cin.get();
}