How is Binary Heap usually implemented?
How is Binary Heap usually implemented?
A Binary Heap is typically implemented as an array due to its properties and the efficiency it offers. Here are the key points regarding its implementation:
Here is a simple example of a Min-Heap implementation in C:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *arr;
int size;
int capacity;
} MinHeap;
MinHeap* createMinHeap(int capacity) {
MinHeap* heap = (MinHeap*)malloc(sizeof(MinHeap));
heap->size = 0;
heap->capacity = capacity;
heap->arr = (int*)malloc(capacity * sizeof(int));
return heap;
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void heapifyUp(MinHeap* heap, int index) {
int parent = (index - 1) / 2;
if (index && heap->arr[parent] > heap->arr[index]) {
swap(&heap->arr[parent], &heap->arr[index]);
heapifyUp(heap, parent);
}
}
void insertMinHeap(MinHeap* heap, int key) {
if (heap->size == heap->capacity) {
printf("Heap overflow\n");
...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào