binarna kopa

This commit is contained in:
Maksym Malko 2020-12-04 06:35:21 +00:00
parent 1690842d28
commit 49aee5ab2c

View File

@ -1,6 +1,117 @@
#include<stdio.h>
#include<stdlib.h>
int main(){
struct heap {
int* array;
int size;
int capacity;
};
int parent(int i){
return (i -1) / 2;
}
int left_child(int i){
return (2*i) + 1;
}
int right_child(int i){
return (2*i) + 2;
}
struct heap* create_heap(int capacity){
struct heap* h = calloc(1,sizeof(struct heap));
h->array = calloc(capacity,sizeof(int));
h->capacity =capacity;
h->size = 0;
return h;
}
void check_heap_property(struct heap* h){
for(int i =0;i<h->size;i++){
int left = left_child(i);
int right = right_child(i);
if(right >= h->size || left>=h->size){
break;
}
if(h->array[i] > h->array[right] || h->array[i] > h->array[left]){
printf("%s\n","Nie je kopa.");
exit(0);
}
}
}
void delete_heap(struct heap* h){
free(h->array);
free(h);
}
void swap(int arr[],int a, int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
void add(struct heap* h,int value){
int i = h->size;//index prvka(posledny)
if(h->size>=capacity){
return;
}
h->size += 1;
h->array[i] = value;
// Pozrieme na jeho rodiča
int p = parent(i);
while(a[i] < a[p]) { // i 0 — мы в корне
swap(h->array,a[i], a[p]);
i = parent(i);
}
}
void print(struct heap* h,int count_spaces,int index){
if(iindex>=h->size){
return ;
}
for(int i =0;i<count_spaces;i++){
printf(" ");
}
printf("%d\n",h->array[index]);
print(h,count_spaces+1,left_child(index));
printAllRight(h,count_spaces+1,right_child(index));
}
int main(){
int i =0;//index of array
int temp_array[25] = {0};
while(scanf("%d",&temp_array[i]) == 1) {
i++;
}
struct heap* h = create_heap(i);
for(int j =0;j<i;j++){
add(h,arr[j]);
}
check_heap_property(h);
puts("Je to taka kopa:");
print(h);
return 0;
}