第6章 堆排序
6.1 堆
最大堆:A[PARENT(i)]>=A[i] 最小堆:A[PARENT(i)]<=A[i]
6.2 维护堆的性质
void HeapAdjust(
int H[],
int s,
int length)
{
int tmp = H[s];
int child =
2*s+
1;
while (child <
length) {
if(child+
1 <
length && H[child]<H[child+
1]) {
++child ;
}
if(H[s]<H[child]) {
H[s] = H[child];
s = child;
child =
2*s+
1;
}
else {
break;
}
H[s] = tmp;
}
6.3 建堆
void BuildingHeap(
int H[],
int length)
{
for (
int i = (
length -
1) /
2 ; i >=
0; --i)
HeapAdjust(H,i,
length);
}
6.4 堆排序
void HeapSort(
int H[],
int length)
{
BuildingHeap(H,
length);
for (
int i =
length -
1; i >
0; --i)
{
int temp = H[i]; H[i] = H[
0]; H[
0] = temp;
HeapAdjust(H,
0, i);
}
}
6.5 优先队列
HeapExtractMax:去掉并返回S中的具有最大键字的元素
int HeapExtractMax(
int H[],
int length)
{
if (
length <
1)
return -
1;
int max = H[
0];
H[
0] = H[
length-
1]
HeapAdjust(H,
0,
length -
1)
return max;
}
HeapIncreaseKey:将元素x的关键字值增加到key
void HeapIncreaseKey(
int H[],
int length,
int i,
int key)
{
if (key < H{i])
return;
H[i] = key
while (i >
0 && H[(i-
1)/
2] < H[i]){
H[i] = H[(i-
1)/
2];
H[(i-
1)/
2] = key;
i = (i-
1)/
2;
}
}
MaxHeapInsert:将新元素x插入到集合S中
int[] MaxHeapInsert(
int H[],
int length,
int key){
int newH[] = new
int[
length +
1];
for (
int i =
0; i <=
length; i++)
newH[i] = H[i];
newH[
length] = -
1;
length++;
HeapIncreaseKey(H,
length,
length -
1, key);
}