?? 10.35.c
字號:
10.35③ 假設定義堆為滿足如下性質的完全三叉樹:
(1) 空樹為堆;
(2) 根結點的值不小于所有子樹根的值,且所有子樹
均為堆。
編寫利用上述定義的堆進行排序的算法,并分析推導
算法的時間復雜度。
實現下列函數:
void HeapSort(HeapType &h);
堆(順序表)的類型HeapType定義如下:
typedef char KeyType;
typedef struct {
KeyType key;
... ...
} RedType;
typedef struct {
RedType r[MAXSIZE+1];
int length;
} SqList, HeapType;
比較函數和交換函數:
Status LT(RedType a, RedType b)
{ return a.key<b.key ? TRUE : FALSE; }
Status GT(RedType a, RedType b)
{ return a.key>b.key ? TRUE : FALSE; }
void Swap(RedType &a, RedType &b)
{ RedType c; c=a; a=b; b=c; }
void Adjust(HeapType &h,int s,int m);
void HeapSort(HeapType &h)
/* 元素比較和交換必須調用以下比較函數和交換函數:*/
/* Status LT(RedType a, RedType b); 比較:"<" */
/* Status GT(RedType a, RedType b); 比較:">" */
/* void Swap(RedType &a, RedType &b); 交換 */
{
int i;
for(i=h.length/3;i>0;i--) Adjust(h,i,h.length);
for(i=h.length;i>1;i--)
{
Swap(h.r[1],h.r[i]);
Adjust(h,1,i-1);
}
}
void Adjust(HeapType &h,int s,int m)
{
RedType rc;
int j;
rc=h.r[s];
for(j=3*s-1;j<=m;j=3*j-1)
{
if(j<m&<(h.r[j],h.r[j+1])){j++; if(j<m&<(h.r[j],h.r[j+1]))j++;}
else if(j<m-1&<(h.r[j],h.r[j+2])) j+=2;
if(!LT(rc,h.r[j])) break;
h.r[s]=h.r[j];
s=j;
}
h.r[s]=rc;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -