堆排序及C语言实现
?排序系列之(2)
堆排序是利用一直特殊的數據結構來完成排序工作的,即“堆”。堆可以被看做一棵完全二叉樹,樹的每一層都會填滿,最后一層可能除外。這種堆有兩種:最大堆和最小堆。在堆排序算法中,使用的是最大堆。最小堆通常在構造優先隊列時使用。最大堆的性質是除了根節點之外的每一個節點,其父節點的值必須大于等于其子節點。即t[parent] >= t[child]
以下是其源代碼實現
view plaincopy to clipboardprint?
/************************************************?
?* 測試從數組0號位開始的堆排序?
?*??
?* 與上面不同的知識點?
?* 1.0號是根元素,則左孩子為2i+1,右孩子為2(i+1);?
?* 2.孩子為i,則父親為i-1/2?
?*??
?*/?
/**?
?* a:?????? 待排序數組?
?* len:???? 數組長度?
?*/?
void heapSort2(int a[],int len)??
{??
??? int i=0;??
??? int maxHeapIndex = len-1;??
??? //首先建堆??
??? for(i=(maxHeapIndex-1)/2;i>=0;i--)??
??? {??
??????? maxHeapify2(a,i,maxHeapIndex);??
??? }??
??? for(i=maxHeapIndex;i>=1;i--)??
??? {??
??????? swap(&a[0],&a[i]);??
??????? // 交換之后,繼續堆化時,堆數組最大索引要減1??
??????? maxHeapify2(a,0,i-1);??
??? }??
}??
/***?
?* a??????????? 待排數組?
?* rootIndex??? 本次堆化的跟?
?* maxHeapIndex 本次堆化所達到的堆數組最大索引?
?*/?
void maxHeapify2(int a[], int rootIndex,int maxHeapIndex)??
{??
??? int lChild = rootIndex*2+1;??
??? int rChild = (rootIndex+1)*2;??
??? int largest = rootIndex;??
??? if(lChild <= maxHeapIndex && a[lChild] > a[rootIndex])??
??????? largest = lChild;??
??? if(rChild <= maxHeapIndex && a[rChild] > a[largest])??
??????? largest = rChild;??
??? if(largest != rootIndex)??
??? {??
??????? swap(&a[largest],&a[rootIndex]);??
??????? maxHeapify2(a,largest,maxHeapIndex);??
??? }??
}??
void heapSortTest2()??
{??
??? int a[] = {5, 18, 151, 138, 160, 63, 174, 169, 79, 200};??
??? int len = sizeof(a)/sizeof(int);??
??? showArray(a,len);??
??? heapSort2(a,len);??
??? showArray(a,len);??
}?
?
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/taizhoufox/archive/2010/10/13/5938616.aspx
總結
- 上一篇: 归并排序及C语言实现
- 下一篇: 希尔排序及C语言实现