I am still learning about C programming, and I am having a bit of an issue with my program.
So my structure is declare in q.h file
#define MAXIMUM_LENGTH 80
struct Tsunami {
unsigned int day;
unsigned int month;
unsigned int year;
unsigned fatalities;
double height;
char location[MAXIMUM_LENGTH];
};
and the function that uses qsort is :
double get_median_height(const struct Tsunami* begin, size_t count)
{
double median = 0;
double compare1,compare2;
struct Tsunami* store = (struct Tsunami*) malloc (sizeof(struct Tsunami) * count);
for (int i = 0; i < (int)count; i++)
{
store[i].month = begin[i].month;
store[i].day = begin[i].day;
store[i].year = begin[i].year;
store[i].fatalities = begin[i].fatalities;
store[i].height = begin[i].height;
strcpy(store[i].location, begin[i].location);
}
qsort(store, count, sizeof(Tsunami), compare_events);
if(count % 2 == 0)
{
printf("%ld",count);
compare1 = store[(count/2)].height;
printf("%lf",compare1);
compare2 = store[(count/2) +1].height;
printf("%lf",compare2);
median = (compare1 + compare2)/2;
}
else
{
median = store[(count/2)].height;
}
free(store);
return median;
}
My compare_events code is
int compare_events(const void* first, const void* second)
{
struct Tsunami* first = (struct Tsunami*)first;
struct Tsunami* second = (struct Tsunami*)second;
return (second->height - first->height);
}
For some reason, it does not help me sort out the value of store.height from smallest to largest. Can someone explain to me why? and how should I use the qsort instead?