|
|
|
@ -0,0 +1,75 @@
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
|
|
void swap(int arr[], int a, int b)
|
|
|
|
|
{
|
|
|
|
|
int tmp;
|
|
|
|
|
tmp = arr[a];
|
|
|
|
|
arr[a] = arr[b];
|
|
|
|
|
arr[b] = tmp;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void heapify(int tree[], int n, int i)
|
|
|
|
|
{
|
|
|
|
|
if (i >= n)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
int max = i;//<2F><><EFBFBD>踸<EFBFBD>ڵ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD>ֵ
|
|
|
|
|
int c1 = 2 * i + 1;
|
|
|
|
|
int c2 = 2 * i + 2; //<2F><><EFBFBD>ӽ<EFBFBD><D3BD><EFBFBD><EFBFBD>±<EFBFBD>Ϊ2i + 1, <20>Һ<EFBFBD><D2BA>ӽ<EFBFBD><D3BD><EFBFBD><EFBFBD>±<EFBFBD>Ϊ2i + 2
|
|
|
|
|
if (c1 < n && tree[c1] > tree[max])
|
|
|
|
|
{//<2F><><EFBFBD>ӵ<EFBFBD><D3B5>±<EFBFBD>ҪС<D2AA><D0A1><EFBFBD>ܽ<EFBFBD><DCBD><EFBFBD><EFBFBD>
|
|
|
|
|
max = c1;//<2F><><EFBFBD>ϴ<EFBFBD>ֵ<EFBFBD>Ľ<EFBFBD><C4BD><EFBFBD>±<EFBFBD><C2B1>¼<EFBFBD><C2BC><EFBFBD><EFBFBD>
|
|
|
|
|
}
|
|
|
|
|
if (c2 < n && tree[c2] > tree[max])
|
|
|
|
|
{
|
|
|
|
|
max = c2;//<2F><><EFBFBD>ϴ<EFBFBD>ֵ<EFBFBD>Ľ<EFBFBD><C4BD><EFBFBD>±<EFBFBD><C2B1>¼<EFBFBD><C2BC><EFBFBD><EFBFBD>
|
|
|
|
|
}
|
|
|
|
|
if (max != i)
|
|
|
|
|
{//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֵ<EFBFBD><D6B5><EFBFBD>Ǹ<EFBFBD><C7B8>ڵ<EFBFBD>
|
|
|
|
|
swap(tree, max, i);//<2F><><EFBFBD><EFBFBD>tree[max]<5D><>tree[i]<5D><>ֵ
|
|
|
|
|
heapify(tree, n, max);//max<61><78><EFBFBD>Ǻ<EFBFBD><C7BA>ӽ<EFBFBD><D3BD><EFBFBD>±<EFBFBD>
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void build_heapify(int tree[], int n)
|
|
|
|
|
{
|
|
|
|
|
int last_node = n - 1;
|
|
|
|
|
int parent = (last_node - 1) / 2;
|
|
|
|
|
int i;
|
|
|
|
|
for (i = parent; i >= 0; i--)
|
|
|
|
|
{
|
|
|
|
|
heapify(tree, n, i);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void heapify_sort(int tree[], int n)
|
|
|
|
|
{
|
|
|
|
|
build_heapify(tree, n);
|
|
|
|
|
int tmp = tree[0];
|
|
|
|
|
for (int i = n - 1; i >= 0; i--)
|
|
|
|
|
{//<2F><><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD>㿪ʼ
|
|
|
|
|
swap(tree, i, 0);
|
|
|
|
|
heapify(tree, i, 0);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int main(){
|
|
|
|
|
int tree[] = { 22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70 };
|
|
|
|
|
int n = 14;
|
|
|
|
|
printf("ԭ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ:");
|
|
|
|
|
for (int i = 0; i < n; i++)
|
|
|
|
|
{
|
|
|
|
|
printf("%d ", tree[i]);
|
|
|
|
|
}
|
|
|
|
|
printf("\n");
|
|
|
|
|
heapify_sort(tree, n);
|
|
|
|
|
printf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><EFBFBD>");
|
|
|
|
|
for (int i = 0; i < n; i++)
|
|
|
|
|
{
|
|
|
|
|
printf("%d ", tree[i]);
|
|
|
|
|
}
|
|
|
|
|
printf("\n");
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|
|