Skip to content

Instantly share code, notes, and snippets.

@Jules-Baratoux
Last active May 16, 2022 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jules-Baratoux/1b1726e6bbe8e08d345b to your computer and use it in GitHub Desktop.
Save Jules-Baratoux/1b1726e6bbe8e08d345b to your computer and use it in GitHub Desktop.
Homework #7 – outputSorted
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <alloca.h>
#include <assert.h>
#include "heap.h"
typedef struct Person_
{
const char* name;
int age;
double height;
} Person;
static void destroy(void* data)
{
(void)data;
}
static int person_print(const Person* people)
{
return printf("{ %-6s age:%i %.2fm }", people->name, people->age, people->height);
}
void outputSorted(const Person people[], int count, int (* compare)(const void *key1, const void *key2))
{
if (count > 0)
{
int i;
Heap* heap = alloca(sizeof(*heap));
heap_init(heap, compare, destroy);
for (i = 0; i < count; ++i)
{
assert(heap_insert(heap, people + i) == 0);
}
assert(heap_size(heap) == count);
while (heap_size(heap) > 0)
{
void* person;
assert(heap_extract(heap, &person) == 0);
assert(person != NULL);
person_print(person);
printf("\n");
}
heap_destroy(heap);
}
}
static int compare_ascending_name(const void* key1, const void* key2)
{
return strcmp(((Person*)key2)->name, ((Person*)key1)->name);
}
static int compare_ascending_age(const void* key1, const void* key2)
{
return ((Person*)key2)->age - ((Person*)key1)->age;
}
#define COEF 1000
static int compare_ascending_height(const void* key1, const void* key2)
{
return ((Person*)key2)->height * COEF - ((Person*)key1)->height * COEF;
}
#define sizeof_array(PTR) (sizeof(PTR) / sizeof(*(PTR)))
int main(void)
{
static const Person people[] =
{
// NAME AGE HEIGHT
{ "Alex", 24, 1.80 },
{ "Bob", 32, 1.78 },
{ "Jack", 43, 1.69 },
{ "Max", 18, 1.85 },
{ "Anna", 47, 1.59 },
{ "Chiara", 52, 1.65 }
};
printf("Output people sorted by ascending name:\n");
outputSorted(people, sizeof_array(people), compare_ascending_name);
printf("\n");
// c) Output people sorted by ascending age.
printf("Output people sorted by ascending age:\n");
outputSorted(people, sizeof_array(people), compare_ascending_age);
printf("\n");
// d) Output people sorted by ascending height.
printf("Output people sorted by ascending height:\n");
outputSorted(people, sizeof_array(people), compare_ascending_height);
printf("\n");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment