把上述c语言代码补充完整
时间: 2024-10-15 16:07:11 浏览: 20
平衡二叉树实现代码
由于我之前提到的是一个伪代码框架,下面是一个完整的C语言代码实现,使用了`min-heap`结构来保持前k个最大的数:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
struct MinHeap {
Node* root;
int size;
};
void create_min_heap(MinHeap* min_heap) {
min_heap->root = NULL;
min_heap->size = 0;
}
int parent(int pos) {
return (pos - 1) / 2;
}
void swap(Node** a, Node** b) {
Node* temp = *a;
*a = *b;
*b = temp;
}
void heapify(MinHeap* min_heap, int pos) {
int smallest = pos;
int left = 2 * pos + 1;
int right = 2 * pos + 2;
if (left < min_heap->size && min_heap->array[left].data < min_heap->array[pos].data)
smallest = left;
if (right < min_heap->size && min_heap->array[right].data < min_heap->array[smallest].data)
smallest = right;
if (smallest != pos) {
swap(&min_heap->array[pos], &min_heap->array[smallest]);
heapify(min_heap, smallest);
}
}
void insert(MinHeap* min_heap, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
if (min_heap->size == 0) {
min_heap->root = newNode;
} else {
newNode->parent = min_heap->root;
insertHelper(min_heap, newNode);
}
min_heap->size++;
}
void insertHelper(MinHeap* min_heap, Node* newNode) {
if (newNode->data < min_heap->array[parent(newNode->pos)].data) {
swap(&min_heap->array[newNode->pos], &min_heap->array[parent(newNode->pos)]);
newNode->parent = min_heap->array[parent(newNode->pos)];
if (newNode->pos != 0)
insertHelper(min_heap, newNode);
} else {
while (newNode->parent && newNode->data < min_heap->array[parent(newNode->pos)].data) {
swap(&min_heap->array[newNode->pos], &min_heap->array[parent(newNode->pos)]);
newNode->parent = min_heap->array[parent(newNode->pos)];
}
}
}
void find_k_largest_sorted_array(int arr[], int k, int n, int h[]) {
MinHeap min_heap;
create_min_heap(&min_heap);
for (int i = 0; i < n; i++) {
insert(&min_heap, arr[i]);
if (min_heap.size > k) {
int largest = min_heap.array[0].data;
min_heap.array[0] = min_heap.array[min_heap.size - 1];
min_heap.size--;
heapify(&min_heap, 0);
free(min_heap.array[min_heap.size]);
}
}
printf("前 %d 大的数是: ", k);
for (int i = 0; i < k; i++)
printf("%d ", min_heap.array[i].data);
printf("\n");
}
int main() {
int arr[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
int k = 3;
int n = sizeof(arr) / sizeof(arr[0]);
int h[n];
find_k_largest_sorted_array(arr, k, n, h);
return 0;
}
```
这段代码首先创建了一个最小堆,然后遍历输入数组,每当插入一个新元素时,如果堆的大小超过k,就删除堆顶(即当前第k+1大的元素),并将最后一个元素移到堆顶并调整堆。最后,打印出前k大的元素。
阅读全文