ADT MAXHEAP在C中的实现
创始人
2024-07-28 20:30:27
0

以下是一种可能的ADT MAXHEAP的C语言实现示例:

#include 
#include 

#define MAX_SIZE 100

typedef struct {
    int* array;
    int size;
    int capacity;
} MaxHeap;

MaxHeap* createMaxHeap(int capacity) {
    MaxHeap* heap = (MaxHeap*)malloc(sizeof(MaxHeap));
    heap->array = (int*)malloc(sizeof(int) * (capacity + 1));
    heap->size = 0;
    heap->capacity = capacity;
    return heap;
}

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void insert(MaxHeap* heap, int value) {
    if (heap->size == heap->capacity) {
        printf("Heap is full\n");
        return;
    }
    
    heap->size++;
    int i = heap->size;
    heap->array[i] = value;
    
    while (i > 1 && heap->array[i/2] < heap->array[i]) {
        swap(&heap->array[i/2], &heap->array[i]);
        i = i/2;
    }
}

void heapify(MaxHeap* heap, int i) {
    int largest = i;
    int left = 2 * i;
    int right = 2 * i + 1;
    
    if (left <= heap->size && heap->array[left] > heap->array[largest]) {
        largest = left;
    }
    
    if (right <= heap->size && heap->array[right] > heap->array[largest]) {
        largest = right;
    }
    
    if (largest != i) {
        swap(&heap->array[i], &heap->array[largest]);
        heapify(heap, largest);
    }
}

int extractMax(MaxHeap* heap) {
    if (heap->size == 0) {
        printf("Heap is empty\n");
        return -1;
    }
    
    int max = heap->array[1];
    heap->array[1] = heap->array[heap->size];
    heap->size--;
    heapify(heap, 1);
    
    return max;
}

void printHeap(MaxHeap* heap) {
    printf("Heap: ");
    for (int i = 1; i <= heap->size; i++) {
        printf("%d ", heap->array[i]);
    }
    printf("\n");
}

int main() {
    MaxHeap* heap = createMaxHeap(MAX_SIZE);
    
    insert(heap, 5);
    insert(heap, 10);
    insert(heap, 8);
    insert(heap, 3);
    insert(heap, 6);
    
    printHeap(heap);
    
    int max = extractMax(heap);
    printf("Extracted max: %d\n", max);
    
    printHeap(heap);
    
    free(heap->array);
    free(heap);
    
    return 0;
}

这是一个基本的最大堆(Max Heap)的实现,其中包含了一些常用的操作,如插入、堆化和提取最大值。请注意,此实现假设数组中的索引从1开始,而不是从0开始。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...