You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

5.
5.1
1(R1,R2.Rn)
2R[1]R[n](R1,R2,Rn-1)(Rn),
R[1,2n-1]<=R[n]
3R[1](R1,R2,Rn-1)
R[1](R1,R2.Rn-2)(Rn-1,Rn)
n-1
5.2
O(nlog2n)
O(1)
5.3
#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;//假设父节点为最大值
int c1 = 2 * i + 1;
int c2 = 2 * i + 2; //左孩子结点的下标为2i + 1, 右孩子结点的下标为2i + 2
if (c1 < n && tree[c1] > tree[max])
{//左孩子的下标要小于总结点数
max = c1;//将较大值的结点下标记录下来
}
if (c2 < n && tree[c2] > tree[max])
{
max = c2;//将较大值的结点下标记录下来
}
if (max != i)
{//如果最大值不是根节点
swap(tree, max, i);//交换tree[max]和tree[i]的值
heapify(tree, n, max);//max就是孩子结点下标
}
}
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--)
{//从最后一个结点开始
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("原数组为:");
for (int i = 0; i < n; i++)
{
printf("%d ", tree[i]);
}
printf("\n");
heapify_sort(tree, n);
printf("经过堆排序后的数组为:");
for (int i = 0; i < n; i++)
{
printf("%d ", tree[i]);
}
printf("\n");
return 0;
}
5.4
0.02498s