编辑代码

#include <stdio.h>

void heapify(int heap[], int nodeIndex, int heapBottom){
    int lastParentIndex = heapBottom / 2;
    while(nodeIndex <= lastParentIndex){
        int leftChildIndex = nodeIndex * 2;
        int maxIndex = leftChildIndex;
        if((leftChildIndex + 1 <= heapBottom) && (heap[leftChildIndex + 1] > heap[leftChildIndex])){
            maxIndex = leftChildIndex + 1;
        }
        if(heap[nodeIndex] < heap[maxIndex]){
            int temp = heap[nodeIndex];
            heap[nodeIndex] = heap[maxIndex];
            heap[maxIndex] = temp;
            nodeIndex = maxIndex;
        }else{
            break;
        }
    }
}

void heapFromBottom(int array[], int length){
    int heap[length + 1];
    int capacity = length;
    for(int i = 0; i < length; i++){
        heap[i + 1] = array[i];
    }
    
    int lastParentIndex = length / 2;
    for(int i = lastParentIndex; i > 0; i--){
        heapify(heap, i, capacity);
    }
    
    int heapTop = 1;
    int heapBottom = capacity;
    while(heapTop < heapBottom){
        int temp = heap[heapTop];
        heap[heapTop] = heap[heapBottom];
        heap[heapBottom] = temp;
        heapBottom--;
        heapify(heap, heapTop, heapBottom);
    }

    for(int i = 1; i <= length; i++){
        array[i - 1] = heap[i];
    }
}

int main () {
    int array[] = {11, 8, 3, 9, 7, 1, 2, 5, 15};
    int length = sizeof(array) / sizeof(array[0]);
    printf("排序前:");
    for(int i = 0; i < length; i++){
        printf("%d ", array[i]);
    }
    heapFromBottom(array, length);
    printf("\n排序后:");
    for(int i = 0; i < length; i++){
        printf("%d ", array[i]);
    }
    return 0;
}