heap push

This commit is contained in:
bronku 2025-10-22 17:10:51 +02:00
parent 7916f181c5
commit 83061c4658
2 changed files with 26 additions and 11 deletions

31
heap.c
View file

@ -1,28 +1,45 @@
#include "heap.h" #include "heap.h"
#include "status_codes.h" #include "status_codes.h"
// #unteasted
int heap_push(heap* h, heap_record* in) int heap_push(heap* h, heap_record* in)
{ {
if (h->length >= h->capacity) { if (h->length >= h->capacity) {
return NO_SPACE; return NO_SPACE;
} }
int index = h->length; int current_index = h->length;
h->length++; h->length++;
heap_record* last = h->location; heap_record* last = h->location;
last += index; last += current_index;
*last = *in; *last = *in;
if (index == 0) { if (current_index == 0) {
return SUCCESS; return SUCCESS;
} }
int parent_index = (current_index - 1) / 2;
// check if violated heap property // check if violated heap property
heap_record* parent = h->location; heap_record* parent = h->location;
parent += ((index - 1) / 2); parent += parent_index;
while (parent->g > last->g) { heap_record* current = h->location;
// just swap them, and check again? current += current_index;
}
// swim up // swim up
while (current_index != 0 && h->compare(parent, current) == 1) {
// current, parent = parent, current
heap_record tmp = *current;
*current = *parent;
*parent = tmp;
// current_index = parent_index
current_index = parent_index;
// parent_index = (current_index -1 )/2
parent_index = (current_index - 1) / 2;
// current = loc[current_index]
current = h->location;
current += current_index;
// parent = loc[parent_index]
parent = h->location;
parent_index += parent_index;
}
return SUCCESS; return SUCCESS;
} }

6
heap.h
View file

@ -1,13 +1,10 @@
#pragma once #pragma once
#include "record.h"
#include "stdbool.h" #include "stdbool.h"
typedef struct { typedef struct {
record* location; int index;
int g;
int buffer_id; int buffer_id;
bool is_blank;
} heap_record; } heap_record;
// almost the same as typedef buffer, but the usage is different, so I think it can be repeated // almost the same as typedef buffer, but the usage is different, so I think it can be repeated
@ -15,6 +12,7 @@ typedef struct {
heap_record* location; heap_record* location;
int length; int length;
int capacity; int capacity;
int (*compare)(const void* a, const void* b);
} heap; } heap;
heap new_heap(int size); heap new_heap(int size);