编辑代码

#include <stdio.h>
#include <stdlib.h>

// 自底向上调整堆
void heapifyUp(int arr[], int n, int i) {
    int parent = (i-1) / 2;
    if (parent >= 0 && arr[parent] < arr[i]) {
        int temp = arr[parent];
        arr[parent] = arr[i];
        arr[i] = temp;
        heapifyUp(arr, n, parent);
    }
}

// 构建堆
void buildHeap(int arr[], int n) {
    for (int i = 1; i < n; i++) {
        heapifyUp(arr, n, i);
    }
}

// 打印堆
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int n1 = 10;
    int arr1[] = {4, 10, 3, 5, 1, 7, 8, 9, 6, 2};
    printf("用例1:原始数组:\n");
    printArray(arr1, n1);
    buildHeap(arr1, n1);
    printf("用例1:构建堆后的数组:\n");
    printArray(arr1, n1);

    int n2 = 9;
    int arr2[] = { 8, 9, 6, 2, 4, 3, 5, 1, 7};
    printf("用例2:原始数组:\n");
    printArray(arr2, n2);
    buildHeap(arr2, n2);
    printf("用例2:构建堆后的数组:\n");
    printArray(arr2, n2);

    int n3 = 6;
    int arr3[] = {10, 3, 1, 8, 9, 2};
    printf("用例3:原始数组:\n");
    printArray(arr3, n3);
    buildHeap(arr3, n3);
    printf("用例3:构建堆后的数组:\n");
    printArray(arr3, n3);
    return 0;
}