#include <cstdio>
#include <stdlib.h>
#include <time.h>
void HeapAdjust(int arr[], int k, int len);
void heap(long A[], long len) {
int arr[25] = { 0 };
for (int i = len; i >= 0; i--)
if (arr[1] < A[i]) {
arr[1] = A[i]; //堆顶<目标值,用A[i]取代
for (int j = 5; j > 0; j--) HeapAdjust(arr, j, 10);
}//反复调整堆
for (int k = 1; k < 11; k++) printf("%d ", arr[k]);
};
void HeapAdjust(int arr[], int k, int len) {
arr[0] = arr[k];//arr[0]暂存子树的根结点
for (int i = 2 * k; i <= len; i *= 2) { //沿key较大的子结点向下筛选
if (i < len && arr[i] > arr[i + 1]) i++; //取key较小的子结点的下标
if (arr[0] >= arr[i])
{
arr[k] = arr[i]; //将A[i]调整到双亲结点上
k = i; //修改k值,以便继续向下筛选
}else break; //筛选结束
}
arr[k] = arr[0]; //被筛选结点的值放入最终位置
};
int main()
{
long arr[1005] = { 0 };
srand((unsigned int)(time(NULL)));//随机数生成
for (int i = 0; i < 1005; i++) arr[i] = (rand() % 1000) + 1;
heap(arr, 1000);
return 0;
};
05-26
2553
09-04
9692
03-23
273