一,线性的数组可以看成一个二差堆,堆中父节点与左孩子的关键码关系为:left=parent*2+1;
堆排序思想:每次循环从二叉堆中将最大的元素shiftup上移至根节点,再将根节点与最后对末尾的元素交换。撇开末尾元素,如此再继续找出下一个最大元素,将此最大元素与此末尾元素交换。依此重复查找最大元素,然后交换。
1.堆排序与插入排序思想有点类似。
2.时间复杂度为nlog2(n);
int heap[]={53,17,78,9,45,65,87,23};
void swap(int *a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}
void getMax(int cus,int end){
while(cus>=0){
int left=cus*2+1;
int max=left;
if(max<end&&heap[left]<heap[left+1])
max++;
if(heap[max]>heap[cus])
swap(&heap[max],&heap[cus]);
cus--;
}
}
void heapSort(const int s){
int size=s,current;
while(size>1){
current=(size-2)/2;
getMax(current,size-1);
swap(&heap[0],&heap[size-1]);
size--;
}
}
int main(){
// minHeap(8);
show();
heapSort(8);
show();
return 0;
}