其實建堆和堆排序十分的簡單,就是不斷的向下調整的過程
建堆是從floor(2/i)處開始,一直到根節點,依次不斷的向下調整
堆排序是從最後一個節點不斷的與第一個根節點交換,然後再讓第一
個節點不斷的向下的調整
#include<bits/stdc++.h>
using namespace std;
int a[15]={-1000,1,5,6,3,9,5,4,2,7,7};
int n=10;//表示數組的長度
void adjust_down(int i,int len)//這個程序省略了結束條件
{
int left=2*i;
int right=2*i+1;
int m=i;//記錄最大值
if(left<=len&&a[m]<a[left])
{
m=left;
}
if(right<=len&&a[m]<a[right])
{
m=right;
}
if(m!=i)//如果左右孩子都不滿足,就不需要繼續向下跟新了
{
swap(a[m],a[i]);
adjust_down(m,len);
}
}
void build_heap()
{
for(int i=n/2;i>=1;i--)
{
adjust_down(i,n);
}
}
void heap_sort()
{
for(int i=n;i>=2;i--)//調整n-1次就行了
{
swap(a[i],a[1]);
adjust_down(1,i-1);
}
}
int main()
{
build_heap();
heap_sort();
for(int i=1;i<=n;i++)
{
cout<<a[i]<<" ";
}
}
向堆中插入一個元素的話,把這個元素放到數組的最後,然後不斷向上調整一下就好了,調整的時候只需要與父親節點比較一下就好了,父親節點不需要考慮另一個孩子節點就行了
void adjust_up(int i,int top)//top一般指1
{
int root=i/2;
if(root>=top&&a[i]>a[root])
{
swap(a[i],a[root]);
adjust_up(root,1);
}
}