一,線性的數組可以看成一個二差堆,堆中父節點與左孩子的關鍵碼關係爲: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;
}