usaa21/a4/program.c

124 lines
2.0 KiB
C
Raw Permalink Normal View History

2021-12-02 12:19:19 +00:00
#include<stdio.h>
#include<stdlib.h>
#define LINESIZE 100
struct heap {
int size;
2021-12-28 15:21:01 +00:00
int* line;
2021-12-02 12:19:19 +00:00
int capacity;
};
int parent(int i){
return (i -1) / 2;
}
int lavy_syn(int i){
return (2*i) + 1;
}
int pravy_syn(int i){
return (2*i) + 2;
}
struct heap* create_heap(int capacity){
struct heap* h = calloc(1,sizeof(struct heap));
2021-12-28 15:21:01 +00:00
h->line = calloc(capacity,sizeof(int));
2021-12-02 12:19:19 +00:00
h->capacity =capacity;
h->size = 0;
return h;
}
void check_heap_property(struct heap* h){
for(int i =0;i<h->size;i++){
int lavy = lavy_syn(i);
int pravy = pravy_syn(i);
if(pravy >= h->size || lavy>=h->size){
break;
}
2021-12-28 15:21:01 +00:00
if(h->line[i] > h->line[pravy] || h->line[i] > h->line[lavy]){
2021-12-02 12:19:19 +00:00
printf("%s\n","Niejekopa.");
exit(0);
}
}
}
void delete_heap(struct heap* h){
2021-12-28 15:21:01 +00:00
free(h->line);
2021-12-02 12:19:19 +00:00
free(h);
}
2021-12-28 15:21:01 +00:00
//void vymen(int arr[],int a, int b){
// int pom = arr[a];
// arr[a] = arr[b];
// arr[b] = pom;
//}
2021-12-02 12:19:19 +00:00
void add(struct heap* h,int value){
int i = h->size;
if(h->size>=h->capacity){
return;
}
h->size += 1;
2021-12-28 15:21:01 +00:00
h->line[i] = value;
2021-12-02 12:19:19 +00:00
}
void print(struct heap* h,int count_spaces,int index){
if(index>=h->size){
return ;
}
for(int i =0;i<count_spaces;i++){
printf(" ");
}
2021-12-28 15:21:01 +00:00
printf("%d\n",h->line[index]);
2021-12-02 12:19:19 +00:00
print(h,count_spaces+1,lavy_syn(index));
print(h,count_spaces+1,pravy_syn(index));
}
void sort(struct heap *h){
int i = h->size-1;
int p = parent(i);
2021-12-28 15:21:01 +00:00
while(h->line[i] < h->line[p]) {
int arr[] = h->line;
int pom = arr[i];
arr[i] = arr[p];
arr[p] = pom;
//vymen(h->line,i, p);
2021-12-02 12:19:19 +00:00
i = parent(i);
}
}
int main(){
2021-12-28 15:21:01 +00:00
int i = 0;
int temp_line[LINESIZE] = {0};
2021-12-02 12:19:19 +00:00
2021-12-28 15:21:01 +00:00
while(scanf("%d",&temp_line[i])== 1) {
2021-12-02 12:19:19 +00:00
i++;
}
struct heap* h = create_heap(i);
for(int j =0;j<i;j++){
2021-12-28 15:21:01 +00:00
add(h,temp_line[j]);
2021-12-02 12:19:19 +00:00
}
check_heap_property(h);
sort(h);
puts("Jetotakakopa:");
print(h,0,0);
return 0;
}